Exemple #1
0
    def _run_interface(self, runtime):
        if not isdefined(self.inputs.out_file):
            self.inputs.out_file = self._gen_output(self.inputs.in_file)

        nii2mncNode = nii2mnc()
        nii2mncNode.inputs.in_file = self.inputs.in_file
        nii2mncNode.inputs.out_file = os.getcwd() + os.sep + str(
            np.random.randint(0, 9999999)) + ".mnc"
        nii2mncNode.run()

        rsl1 = minc.Resample()
        rsl1.inputs.input_file = nii2mncNode.inputs.out_file
        rsl1.inputs.output_file = os.getcwd() + os.sep + str(
            np.random.randint(0, 9999999)) + ".mnc"
        rsl1.inputs.like = self.inputs.template
        print(rsl1.cmdline)
        rsl1.run()

        beast = mincbeastCommand()
        beast.inputs.out_file = os.getcwd() + os.sep + "beast_mask_" + str(
            np.random.randint(0, 9999999)) + ".mnc"
        beast.inputs.in_file = rsl1.inputs.output_file
        beast.inputs.library_dir = self.inputs.library_dir
        beast.inputs.voxel_size = self.inputs.voxel_size
        beast.inputs.same_resolution = self.inputs.same_resolution
        beast.inputs.median = self.inputs.median
        beast.inputs.fill = self.inputs.fill
        beast.inputs.configuration = self.inputs.configuration
        beast.run()

        rsl2 = minc.Resample()
        rsl2.inputs.input_file = beast.inputs.out_file
        rsl2.inputs.like = self.inputs.nii2mncNode.inputs.out_file
        rsl2.inputs.nearest_neighbour_interpolation = True
        print(rsl2.cmdline)
        rsl2.run()

        mnc2niiNode = mnc2nii()
        mnc2niiNode.inputs.in_file = rsl2.inputs.output_file
        mnc2niiNode.inputs.out_file = self.inputs.out_file
        mnc2niiNode.run()
        print(resample.cmdline)
        resample.run()
        return runtime
Exemple #2
0
def create_alt_template(template, beast_dir, clobber=False):
    template_rsl = os.path.splitext(template)[0] + '_rsl.mnc'
    mask = os.path.splitext(template)[0] + '_mask.mnc'
    mask_rsl_fn = os.path.splitext(template)[0] + '_rsl_mask.mnc'

    for f in glob.glob(beast_dir + os.sep + "*mnc"):
        if not os.path.exists(template_rsl) or clobber:
            rsl = minc.Resample()
            rsl.inputs.input_file = template
            rsl.inputs.output_file = template_rsl
            rsl.inputs.like = f
            print rsl.cmdline
            rsl.run()

        if not os.path.exists(mask_rsl_fn) or clobber:
            mask_rsl = minc.Resample()
            mask_rsl.inputs.input_file = mask
            mask_rsl.inputs.output_file = mask_rsl_fn
            mask_rsl.inputs.like = f
            mask_rsl.run()
            print(mask_rsl.cmdline)
            break
    return template_rsl
Exemple #3
0
def ecattomincWorkflow(name):
    workflow = pe.Workflow(name=name)
    #Define input node that will receive input from outside of workflow
    inputNode = pe.Node(niu.IdentityInterface(fields=["in_file", "header"]), name='inputNode')
    conversionNode = pe.Node(interface=ecattomincCommand(), name="conversionNode")
    mincConversionNode = pe.Node(interface=mincconvertCommand(), name="mincConversionNode")
    fixHeaderNode = pe.Node(interface=FixHeaderCommand(), name="fixHeaderNode")
    paramNode = pe.Node(interface=param2xfmCommand(), name="param2xfmNode")
    paramNode.inputs.rotation = "0 180 0"
    resampleNode = pe.Node(interface=minc.Resample(), name="resampleNode")
    resampleNode.inputs.vio_transform=True
    outputNode  = pe.Node(niu.IdentityInterface(fields=["out_file"]), name='outputNode')

    workflow.connect(inputNode, 'in_file', conversionNode, 'in_file')
    workflow.connect(conversionNode, 'out_file', fixHeaderNode, 'in_file')
    workflow.connect(inputNode, 'header', fixHeaderNode, 'header')
    workflow.connect(fixHeaderNode, 'out_file', outputNode, 'out_file')

    return(workflow)
def get_workflow(name, infosource, opts):
    '''
        Create workflow to perform PET to T1 co-registration.

        1. PET to T1 coregistration with brain masks
        2. PET to T1 coregistration without brain masks (OPTIONAL)
        3. Transform T1 MRI brainmask and headmask from MNI 152 to T1 native
        4. Resample 4d PET image to T1 space
        5. Resample 4d PET image to MNI 152 space

        :param name: Name for workflow
        :param infosource: Infosource for basic variables like subject id (sid) and condition id (cid)
        :param datasink: Node in which output data is sent
        :param opts: User options
        
        :returns: workflow
    '''
    workflow = pe.Workflow(name=name)
    #Define input node that will receive input from outside of workflow
    inputnode = pe.Node(niu.IdentityInterface(fields=["pet_volume","pet_volume_4d","nativeT1nuc","t1_headMask","tka_label_img_t1","results_label_img_t1","pvc_label_img_t1", "t1_brain_mask", "xfmT1MNI", "T1Tal", "error", "header" ]), name='inputnode')
    #Define empty node for output
    outputnode = pe.Node(niu.IdentityInterface(fields=["petmri_img", "petmri_img_4d","petmni_img_4d","petmri_xfm","mripet_xfm",'petmni_xfm', 'mnipet_xfm' ]), name='outputnode')

    node_name="pet_brainmask"
    petMasking = pe.Node(interface=PETheadMasking(), name=node_name)
    petMasking.inputs.slice_factor = opts.slice_factor
    petMasking.inputs.total_factor = opts.total_factor
    workflow.connect(inputnode, 'pet_volume', petMasking, 'in_file')
    workflow.connect(inputnode, 'header', petMasking, 'in_json')

    #node_name="pet2mri_withMask"
    #pet2mri_withMask = pe.Node(interface=PETtoT1LinRegRunning(), name=node_name)
    #pet2mri_withMask.inputs.clobber = True
    #pet2mri_withMask.inputs.verbose = opts.verbose
    #pet2mri_withMask.inputs.lsq="lsq6"

    
    #if opts.no_mask :
    node_name="pet2mri"
    pet2mri = pe.Node(interface=PETtoT1LinRegRunning(), name=node_name)
    pet2mri.inputs.clobber = True
    pet2mri.inputs.verbose = opts.verbose
    pet2mri.inputs.lsq="lsq6"
    pet2mri.inputs.metric="mi"
    #else : 
    #pet2mri = pet2mri_withMask
    final_pet2mri = pet2mri

    if isdefined(inputnode.inputs.error) : 
        final_pet2mri.inputs.error = error

    node_name="t1_brain_mask_pet-space"
    pet_brain_mask = pe.Node(interface=minc.Resample(), name=node_name)
    pet_brain_mask.inputs.nearest_neighbour_interpolation = True
    pet_brain_mask.inputs.clobber = True
    pet_brain_mask_img = 'output_file'
    
    workflow.connect([(inputnode, pet_brain_mask, [('t1_brain_mask', 'input_file' )]),
                        (inputnode, pet_brain_mask, [('pet_volume', 'like')]), 
                        (pet2mri, pet_brain_mask, [('out_file_xfm_invert', 'transformation')])
                    ]) 


    if opts.calculate_t1_pet_space :
        t1_pet_space = pe.Node(interface=minc.Resample(), name="t1_pet_space")
        t1_pet_space.inputs.clobber = True
        workflow.connect([(inputnode, t1_pet_space, [('nativeT1nuc', 'input_file' )]),
                            (inputnode, t1_pet_space, [('pet_volume', 'like')]), 
                            (pet2mri, t1_pet_space, [('out_file_xfm_invert', 'transformation')])
                        ]) 

    #if opts.no_mask :
        workflow.connect([(inputnode, pet2mri, [('pet_volume', 'in_source_file')]),
                          (inputnode, pet2mri, [('nativeT1nuc', 'in_target_file')])#,
                          #(petMasking, pet2mri, [('out_file', 'in_source_mask')]), 
                          #(inputnode, pet2mri, [('pet_volume', 'init_file_xfm')])
                          #(pet2mri_withMask, pet2mri, [('out_file_xfm', 'init_file_xfm')])
                          ]) 

    #workflow.connect([(inputnode, pet2mri_withMask, [('pet_volume', 'in_source_file')]),
                      #(petMasking, pet2mri_withMask, [('out_file', 'in_source_mask')]), 
                      #(inputnode, pet2mri_withMask, [('nativeT1nuc', 'in_target_file')])
                      #]) 
    
    #if opts.coregistration_brain_mask :
        #workflow.connect(inputnode, 't1_brain_mask',  pet2mri_withMask, 'in_target_mask')
        #workflow.connect(inputnode, 't1_brain_mask',  pet2mri, 'in_target_mask')
    
    if opts.test_group_qc :
        ###Create rotation xfm files based on transform error
        transformNode = pe.Node(interface=rsl.param2xfmInterfaceCommand(), name='transformNode')
        workflow.connect(inputnode, 'error', transformNode, 'transformation')
        
        ### Concatenate pet2mri and misalignment xfm
        pet2misalign_xfm=pe.Node(interface=ConcatCommand(), name="pet2misalign_xfm")
        workflow.connect(pet2mri,'out_file_xfm', pet2misalign_xfm, 'in_file')
        workflow.connect(transformNode,'out_file', pet2misalign_xfm, 'in_file_2')

        ###Apply transformation to PET file
        transform_resampleNode=pe.Node(interface=rsl.ResampleCommand(),name="transform_resampleNode")
        transform_resampleNode.inputs.use_input_sampling=True;
        workflow.connect(transformNode, 'out_file', transform_resampleNode, 'transformation')
        workflow.connect(pet2mri, 'out_file_img', transform_resampleNode, 'in_file')
        #workflow.connect(pet2misalign_xfm, 'out_file', transform_resampleNode, 'transformation')

        ###Rotate brain mask
        transform_brainmaskNode=pe.Node(interface=rsl.ResampleCommand(), name="transform_brainmaskNode" )
        transform_brainmaskNode.inputs.interpolation='nearest_neighbour'
        workflow.connect(pet2misalign_xfm, 'out_file', transform_brainmaskNode, 'transformation')
        workflow.connect(transform_resampleNode, 'out_file', transform_brainmaskNode, 'model_file')
        workflow.connect(pet_brain_mask, pet_brain_mask_img, transform_brainmaskNode, 'in_file')   

        invert_concat_pet2misalign_xfm=pe.Node(interface=minc.XfmInvert(),name="invert_concat_pet2misalign_xfm")
        workflow.connect(pet2misalign_xfm,'out_file',invert_concat_pet2misalign_xfm,'input_file') 
        pet2mri = final_pet2mri = pe.Node(interface=niu.IdentityInterface(fields=["out_file_img", "out_file_xfm", "out_file_xfm_invert"]), name="pet2mri_misaligned") 
        workflow.connect(transform_resampleNode, "out_file", final_pet2mri, "out_file_img")
        workflow.connect(pet2misalign_xfm, "out_file", final_pet2mri, "out_file_xfm")
        workflow.connect(invert_concat_pet2misalign_xfm, "output_file", final_pet2mri, "out_file_xfm_invert")
        pet_brain_mask = transform_brainmaskNode
        pet_brain_mask_img = 'out_file'
    
    #Resample 4d PET image to T1 space
    pettot1_4d = pe.Node(interface=minc.Resample(), name='pettot1_4d')
    pettot1_4d.inputs.output_file='pet_space-t1_4d.mnc'
    
    workflow.connect(inputnode, 'pet_volume_4d', pettot1_4d, 'input_file')
    workflow.connect(pet2mri, 'out_file_xfm', pettot1_4d, 'transformation')
    workflow.connect(inputnode, 'nativeT1nuc', pettot1_4d, 'like')
	
    #Resample 4d PET image to MNI space

    PETMNIXfm_node = pe.Node( interface=ConcatCommand(), name="PETMNIXfm_node")
    workflow.connect(pet2mri, "out_file_xfm", PETMNIXfm_node, "in_file")
    workflow.connect(inputnode, "xfmT1MNI", PETMNIXfm_node, "in_file_2")

    MNIPETXfm_node = pe.Node(interface=minc.XfmInvert(), name="MNIPETXfm_node")
    workflow.connect( PETMNIXfm_node, "out_file", MNIPETXfm_node, 'input_file'  )

    t1tomni_4d = pe.Node(interface=minc.Resample(), name='t1tomni_4d')
    workflow.connect(pettot1_4d, 'output_file', t1tomni_4d, 'input_file')
    workflow.connect(inputnode, "xfmT1MNI", t1tomni_4d, 'transformation')
    workflow.connect(inputnode, 'T1Tal', t1tomni_4d, 'like')
   
    workflow.connect(PETMNIXfm_node, 'out_file', outputnode, 'petmni_xfm' )
    workflow.connect(MNIPETXfm_node, 'output_file', outputnode, 'mnipet_xfm' )
    workflow.connect(pettot1_4d,'output_file', outputnode, 'petmri_img_4d')
    workflow.connect(t1tomni_4d,'output_file', outputnode, 'petmni_img_4d')
    workflow.connect(final_pet2mri, 'out_file_xfm', outputnode, 'petmri_xfm')
    workflow.connect(final_pet2mri, 'out_file_xfm_invert', outputnode, 'mripet_xfm')
    workflow.connect(final_pet2mri, 'out_file_img', outputnode, 'petmri_img')
    workflow.connect(pet_brain_mask, pet_brain_mask_img, outputnode,'pet_brain_mask' )
    return workflow 
    def _run_interface(self, runtime):
        #tmpDir = tempfile.mkdtemp()
        tmpDir = os.getcwd() + os.sep + 'tmp_nLinReg'
        os.mkdir(tmpDir)
        source = self.inputs.in_source_file
        target = self.inputs.in_target_file
        s_base = basename(os.path.splitext(source)[0])
        t_base = basename(os.path.splitext(target)[0])
        if not isdefined(self.inputs.out_file_xfm):
            self.inputs.out_file_xfm = fname_presuffix(os.getcwd()+os.sep+s_base+"_TO_"+t_base, suffix=self._suffix+'xfm', use_ext=False)
        if not isdefined(self.inputs.out_file_img):
            self.inputs.out_file_img = fname_presuffix(os.getcwd()+os.sep+s_base+"_TO_"+t_base, suffix=self._suffix)

        prev_xfm = None
        if self.inputs.init_file_xfm:
            prev_xfm = self.inputs.init_file_xfm

        if self.inputs.normalize:
            inorm_target = tmpDir+"/"+t_base+"_inorm.mnc"
            inorm_source = tmpDir+"/"+s_base+"_inorm.mnc"

            run_resample = minc.Resample();
            run_resample.inputs.in_file=target
            run_resample.inputs.out_file=inorm_target
            run_resample.inputs.like=source

            if self.inputs.verbose:
                print run_resample.cmdline
            if self.inputs.run:
                run_resample.run()

            run_inormalize = InormalizeCommand();
            run_inormalize.inputs.in_file=source
            run_inormalize.inputs.out_file=inorm_source
            run_inormalize.inputs.model_file=inorm_target
            if self.inputs.verbose:
                print run_inormalize.cmdline
            if self.inputs.run:
                run_inormalize.run()
        else:
            inorm_target = target
            inorm_source = source 


        class tracc_args:
            def __init__(self, nonlinear, weight, stiffness, similarity, sub_lattice):
                # self.debug=debug
                self.nonlinear=nonlinear
                self.weight=weight
                self.stiffness=stiffness
                self.similarity=similarity
                self.sub_lattice=sub_lattice

        class conf:
            def __init__(self, step, blur_fwhm, iterations, lattice_diam):
                self.step=step
                self.blur_fwhm=blur_fwhm
                self.iterations=iterations
                self.lattice_diam=lattice_diam

        conf1 = conf(32,16,20,96)
        conf2 = conf(16,8,20,48)
        conf3 = conf(12,6,20,36)
        conf4 = conf(8,4,20,24)
        conf5 = conf(6,3,20,18)
        conf6 = conf(4,2,10,12)
        conf_list = [ conf1, conf2, conf3, conf4, conf5, conf6 ]
        nonlin_tracc_args = tracc_args('corrcoeff',1.0,1,0.3,6)

        i=1
        for confi in conf_list:
            tmp_source=tmpDir+"/"+s_base+"_fwhm.mnc"
            tmp_source_blur_base=tmpDir+"/"+s_base+"_fwhm"+str(confi.blur_fwhm)
            tmp_source_blur=tmpDir+"/"+s_base+"_fwhm"+str(confi.blur_fwhm)+"_blur.mnc"
            tmp_target=tmpDir+"/"+t_base+"_fwhm.mnc"
            tmp_target_blur_base=tmpDir+"/"+t_base+"_fwhm"+str(confi.blur_fwhm)
            tmp_target_blur=tmpDir+"/"+t_base+"_fwhm"+str(confi.blur_fwhm)+"_blur.mnc"
            tmp_xfm = tmpDir+"/"+t_base+"_conf"+str(i)+".xfm";
            tmp_rspl_vol = tmpDir+"/"+s_base+"_conf"+str(i)+".mnc";

            print '-------+------- iteration'+str(i)+' -------+-------'
            print '       | steps : \t\t'+ str(confi.step)
            print '       | blur_fwhm : \t\t'+ str(confi.blur_fwhm)
            print '       | nonlinear : \t\t'+ str(nonlin_tracc_args.nonlinear)
            print '       | weight : \t\t'+ str(nonlin_tracc_args.weight)
            print '       | stiffness : \t\t'+ str(nonlin_tracc_args.stiffness)
            print '       | similarity : \t\t'+ str(nonlin_tracc_args.similarity)
            print '       | sub_lattice : \t\t'+ str(nonlin_tracc_args.sub_lattice)
            print '       | source : \t\t'+ tmp_source_blur
            print '       | target : \t\t'+ tmp_target_blur
            print '       | xfm : \t\t\t'+ tmp_xfm
            print '       | out : \t\t\t'+ tmp_rspl_vol
            print '\n'

            if self.inputs.in_source_mask and self.inputs.in_target_mask:
                if os.path.isfile(self.inputs.in_source_mask) and not os.path.exists(tmpDir+"/"+s_base+"_masked.mnc"):
                    source = tmpDir+"/"+s_base+"_masked.mnc"
                    run_calc = minc.Calc();
                    run_calc.inputs.input_files = [inorm_source, self.inputs.in_source_mask]
                    run_calc.inputs.output_file = source
                    run_calc.inputs.expression='A[1] > 0.5 ? A[0] : A[1]'
                    if self.inputs.verbose:
                        print run_calc.cmdline
                    if self.inputs.run:
                        run_calc.run()

                if os.path.isfile(self.inputs.in_target_mask) and not os.path.exists(tmpDir+"/"+t_base+"_masked.mnc"):
                    target = tmpDir+"/"+t_base+"_masked.mnc"
                    run_calc.inputs.in_file = [inorm_target, self.inputs.in_target_mask]
                    run_calc.inputs.out_file = target
                    run_calc.inputs.expression='A[1] > 0.5 ? A[0] : A[1]'
                    if self.inputs.verbose:
                        print run_calc.cmdline
                    if self.inputs.run:
                        run_calc.run()
            else:
                source = inorm_source
                target = inorm_target


            run_smooth = minc.Blur();
            run_smooth.inputs.input_file=target
            run_smooth.inputs.fwhm=confi.blur_fwhm
            run_smooth.inputs.output_file_base=tmp_target_blur_base
            if self.inputs.verbose:
                print run_smooth.cmdline
            if self.inputs.run:
                run_smooth.run()

            run_smooth = minc.Blur();
            run_smooth.inputs.input_file=source
            run_smooth.inputs.fwhm=confi.blur_fwhm
            run_smooth.inputs.output_file_base=tmp_source_blur_base
            if self.inputs.verbose:
                print run_smooth.cmdline
            if self.inputs.run:
                run_smooth.run()

            run_tracc = TraccCommand();
            run_tracc.inputs.in_source_file=tmp_source_blur
            run_tracc.inputs.in_target_file=tmp_target_blur
            run_tracc.inputs.steps=str(confi.step)+' '+str(confi.step)+' '+str(confi.step)
            run_tracc.inputs.iterations=confi.iterations
            run_tracc.inputs.nonlinear=nonlin_tracc_args.nonlinear
            run_tracc.inputs.weight=nonlin_tracc_args.weight
            run_tracc.inputs.stiffness=nonlin_tracc_args.stiffness
            run_tracc.inputs.similarity=nonlin_tracc_args.similarity
            run_tracc.inputs.sub_lattice=nonlin_tracc_args.sub_lattice
            run_tracc.inputs.lattice=str(confi.lattice_diam)+' '+str(confi.lattice_diam)+' '+str(confi.lattice_diam)
            if i == len(conf_list):
                run_tracc.inputs.out_file_xfm=self.inputs.out_file_xfm
            else :
                run_tracc.inputs.out_file_xfm=tmp_xfm
            print "\nOutput of minctracc:" +  run_tracc.inputs.out_file_xfm + "\n"
            if i == 1:
                run_tracc.inputs.identity=True
            if prev_xfm:
                run_tracc.inputs.transformation=prev_xfm
            if self.inputs.in_source_mask:
                run_tracc.inputs.in_source_mask=self.inputs.in_source_mask
            if self.inputs.in_target_mask:
                run_tracc.inputs.in_target_mask=self.inputs.in_target_mask

            if self.inputs.verbose:
                print run_tracc.cmdline
            run_tracc.run()

            
            if i == len(conf_list):
                prev_xfm = self.inputs.out_file_xfm
            else :
                prev_xfm = tmp_xfm
            
            run_resample = minc.Resample();
            run_resample.inputs.input_file=source
            run_resample.inputs.output_file=tmp_rspl_vol
            run_resample.inputs.like=target
            run_resample.inputs.transformation=run_tracc.inputs.out_file_xfm
            if self.inputs.verbose:
                print run_resample.cmdline
            if self.inputs.run:
                run_resample.run()

            i += 1


        if isdefined(self.inputs.init_file_xfm):
            run_concat = minc.XfmConcat();
            run_concat.inputs.input_files=[ self.inputs.init_xfm, prev_xfm  ]
            run_concat.inputs.output_file=self.inputs.out_file_xfm
            if self.inputs.verbose:
                print run_concat.cmdline
            if self.inputs.run:
                run_concat.run()

        # else:
        #     if self.inputs.verbose:
        #         cmd=' '.join(['cp', prev_xfm, self.inputs.out_file_xfm])
        #         print(cmd)
        #     if self.inputs.run:
        #         shutil.copy(prev_xfm, self.inputs.out_file_xfm)

        print '\n-+- creating '+self.inputs.out_file_img+' using '+self.inputs.out_file_xfm+' -+-\n'
        run_resample = minc.Resample();
        run_resample.inputs.input_file=self.inputs.in_source_file
        run_resample.inputs.output_file=self.inputs.out_file_img
        run_resample.inputs.like=self.inputs.in_target_file
        run_resample.inputs.transformation=self.inputs.out_file_xfm
        if self.inputs.verbose:
            print run_resample.cmdline
        if self.inputs.run:
            run_resample.run()

        #shutil.rmtree(tmpDir)
        return runtime
    def _run_interface(self, runtime):
        #tmpDir = tempfile.mkdtemp()
        tmpDir = os.getcwd() + os.sep + 'tmp_PETtoT1LinRegRunning'  #tempfile.mkdtemp()
        os.mkdir(tmpDir)
        source = self.inputs.in_source_file
        target = self.inputs.in_target_file
        s_base = basename(os.path.splitext(source)[0])
        t_base = basename(os.path.splitext(target)[0])


        if not isdefined(self.inputs.out_file_xfm):
            self.inputs.out_file_xfm = os.getcwd()+os.sep+s_base+self._suffix+'.xfm'
        if not isdefined(self.inputs.out_file_xfm_invert):
            self.inputs.out_file_xfm_invert = os.getcwd()+os.sep+t_base+self._suffix+'.xfm'
        if not isdefined(self.inputs.out_file_img):
            self.inputs.out_file_img = os.getcwd()+os.sep+s_base+self._suffix+ '.mnc'

        #print("\n\n\n")
        #print( self.inputs.out_file_img )
        #print("\n\n\n")
        #exit(0)

        prev_xfm = None
        if self.inputs.init_file_xfm:
            prev_xfm = self.inputs.init_file_xfm

        source = self.inputs.in_source_file
        target = self.inputs.in_target_file
        s_base = basename(os.path.splitext(source)[0])
        t_base = basename(os.path.splitext(target)[0])

        if self.inputs.in_source_mask and self.inputs.in_target_mask:
            if os.path.isfile(self.inputs.in_source_mask):
                source = tmpDir+"/"+s_base+"_masked.mnc"
                #run_calc = CalcCommand();
                run_calc = minc.Calc();
                #MIC run_calc.inputs.in_file = [self.inputs.in_source_file, self.inputs.in_source_mask]
                run_calc.inputs.input_files = [self.inputs.in_source_file, self.inputs.in_source_mask]
                #MIC run_calc.inputs.out_file = source
                run_calc.inputs.output_file = source

                print 'Source Mask:', source
                # run_calc.inputs.expression='if(A[1]>0.5){out=A[0];}else{out=A[1];}'
                run_calc.inputs.expression='A[1] > 0.5 ? A[0] : A[1]'
                if self.inputs.verbose:
                    print run_calc.cmdline
                if self.inputs.run:
                    run_calc.run()


            if os.path.isfile(self.inputs.in_target_mask):
                target = tmpDir+"/"+t_base+"_masked.mnc"
                run_calc.inputs.input_files = [self.inputs.in_target_file, self.inputs.in_target_mask]
                #run_calc.inputs.out_file = target
                run_calc.inputs.output_file = target

                print 'Target Mask:', target
                run_calc.inputs.expression='A[1] > 0.5 ? A[0] : A[1]'
                if self.inputs.verbose:
                    print run_calc.cmdline
                if self.inputs.run:
                    run_calc.run()

        class conf:
            def __init__(self, type_, est, blur_fwhm_target, blur_fwhm_source, steps, tolerance, simplex, lsq, blur_gradient):
                self.type_=type_
                self.est=est
                self.blur_fwhm_target=blur_fwhm_target
                self.blur_fwhm_source=blur_fwhm_source
                self.steps=steps
                self.tolerance=tolerance
                self.simplex=simplex
                self.lsq=lsq
		self.blur_gradient=blur_gradient
        
        if isdefined( self.inputs.lsq ) :
            lsq0=self.inputs.lsq    
            lsq1=self.inputs.lsq    
            lsq2=self.inputs.lsq    
            lsq3=self.inputs.lsq    
            lsq4=self.inputs.lsq    
        else :
            lsq0="lsq6"
            lsq1="lsq6"    
            lsq2="lsq7"    
            lsq3="lsq9"    
            lsq4="lsq12"    

        #conf1 = conf("blur", "-est_translations", 10, 6, "8 8 8", 0.01, 8, lsq1)
        #conf2 = conf("blur", "", 6, 6, "4 4 4", 0.004, 6, lsq2)
        #conf3 = conf("blur", "", 4, 4, "2 2 2", 0.002, 4, lsq3)
        
        conf0 = conf("blur", "-est_translations", 16, 16, "8 8 8", 0.01, 32, lsq0, False)
        conf1 = conf("blur", "", 8, 8, "4 4 4", 0.004, 16, lsq1, False)
        conf2 = conf("blur", "", 4, 4, "4 4 4", 0.004, 8, lsq2, False)
        conf3 = conf("blur", "", 4, 4, "4 4 4", 0.004, 4, lsq3, True)
        conf4 = conf("blur", "", 2, 2, "2 2 2", 0.004, 2, lsq4, True)

        #conf_list = [ conf0 ] #, conf1, conf2, conf3, conf4 ]
        conf_list = [  conf0, conf1, conf2, conf3, conf4 ]

        i=1
        for confi in conf_list:
            tmp_source=tmpDir+"/"+s_base+"_fwhm"+str(confi.blur_fwhm_source)
            tmp_source_blur_base=tmpDir+"/"+s_base+"_fwhm"+str(confi.blur_fwhm_source)
            tmp_source_blur=tmpDir+"/"+s_base+"_fwhm"+str(confi.blur_fwhm_source)+"_"+confi.type_+".mnc"
            tmp_target=tmpDir+"/"+t_base+"_fwhm"+str(confi.blur_fwhm_target)
            tmp_target_blur_base=tmpDir+"/"+t_base+"_fwhm"+str(confi.blur_fwhm_target)
            tmp_target_blur=tmpDir+"/"+t_base+"_fwhm"+str(confi.blur_fwhm_target)+"_"+confi.type_+".mnc"
            tmp_xfm = tmpDir+"/"+t_base+"_conf"+str(i)+".xfm";
            tmp_rspl_vol = tmpDir+"/"+s_base+"_conf"+str(i)+".mnc";

            print '-------+------- iteration'+str(i)+' -------+-------'
            print '       | steps : \t\t'+ confi.steps
            print '       | lsq : \t\t'+ confi.lsq
            print '       | blur_fwhm_mri : \t'+ str(confi.blur_fwhm_target)
            print '       | blur_fwhm_pet : \t'+ str(confi.blur_fwhm_source)
            print '       | simplex : \t\t'+ str(confi.simplex)
            print '       | source : \t\t'+ tmp_source_blur
            print '       | target : \t\t'+ tmp_target_blur
            print '       | xfm : \t\t\t'+ tmp_xfm
            print '       | out : \t\t\t'+ tmp_rspl_vol
            print '\n'

            run_smooth = minc.Blur();
            run_smooth.inputs.input_file=target
            run_smooth.inputs.fwhm=confi.blur_fwhm_target
            run_smooth.inputs.output_file_base=tmp_target_blur_base
            if confi.blur_gradient :
                run_smooth.inputs.gradient=True
            
            print run_smooth.cmdline
            run_smooth.run()

            run_smooth = minc.Blur();
            run_smooth.inputs.input_file=source
            run_smooth.inputs.fwhm=confi.blur_fwhm_source
            run_smooth.inputs.output_file_base=tmp_source_blur_base
            if confi.blur_gradient :
                run_smooth.inputs.gradient=True
            run_smooth.inputs.no_apodize=True
            
            print run_smooth.cmdline
            run_smooth.run()

            run_tracc = TraccCommand();
            run_tracc.inputs.in_source_file=tmp_source_blur
            run_tracc.inputs.in_target_file=tmp_target_blur
            run_tracc.inputs.out_file_xfm=tmp_xfm
            run_tracc.inputs.objective_func=self.inputs.metric 
            run_tracc.inputs.steps=confi.steps
            run_tracc.inputs.simplex=confi.simplex
            run_tracc.inputs.tolerance=confi.tolerance
            run_tracc.inputs.est=confi.est
            run_tracc.inputs.lsq=confi.lsq 
            if prev_xfm:
                run_tracc.inputs.transformation=prev_xfm
            if self.inputs.in_source_mask:
                run_tracc.inputs.in_source_mask=self.inputs.in_source_mask
            if self.inputs.in_target_mask:
                run_tracc.inputs.in_target_mask=self.inputs.in_target_mask

            print run_tracc.cmdline
            if self.inputs.run:
                run_tracc.run()

            run_resample = minc.Resample();
            run_resample.inputs.input_file=source
            run_resample.inputs.output_file=tmp_rspl_vol
            run_resample.inputs.like=target
            run_resample.inputs.transformation=tmp_xfm
            if self.inputs.verbose:
                print run_resample.cmdline
            if self.inputs.run:
                run_resample.run()

            prev_xfm = tmp_xfm
            i += 1

            print '\n'

     
        #No need for this because the final xfm file includes the initial one
        if isdefined(self.inputs.error):
            ###Create rotation xfm files based on transform error
            transformNode = pe.Node(interface=rsl.param2xfmInterfaceCommand(), name='transformNode')
            transformNode.inputs.error = self.inputs.error 
            
            ###
            run_concat = minc.ConcatCommand();
            run_concat.inputs.in_file=transformNode.inputs.output_file
            run_concat.inputs.in_file_2=tmp_xfm
            run_concat.inputs.out_file=self.inputs.out_file_xfm
            print run_concat.cmdline
            run_concat.run()
            
            tmp_xfm = self.inputs.out_file_xfm
            
            misregister_pet = minc.Resample();
            misregister_pet.inputs.input_file=self.inputs.out_file_img
            #misregister_pet.inputs.output_file=tmpDir+os.sep+"temp_pet_4d_misaligned.mnc" 
            misregister_pet.inputs.use_input_sampling=True
            misregister_pet.inputs.transformation=self.inputs.out_file_xfm
            shutil.copy(self.inputs.output_file, self.inputs.out_file_img)
        else :
            cmd=' '.join(['cp', tmp_xfm, self.inputs.out_file_xfm])
            print(cmd)
            shutil.copy(tmp_xfm, self.inputs.out_file_xfm)

        #Invert transformation
        run_xfmpetinvert = minc.XfmInvert();
        run_xfmpetinvert.inputs.input_file = self.inputs.out_file_xfm
        run_xfmpetinvert.inputs.output_file = self.inputs.out_file_xfm_invert
        if self.inputs.verbose:
            print run_xfmpetinvert.cmdline
        if self.inputs.run:
            run_xfmpetinvert.run()



        #if self.inputs.out_file_img:
        print '\n-+- Resample 3d PET image -+-\n'
        run_resample = minc.Resample();
        run_resample.inputs.input_file=self.inputs.in_source_file
        run_resample.inputs.output_file=self.inputs.out_file_img
        run_resample.inputs.like=self.inputs.in_target_file
        run_resample.inputs.transformation=self.inputs.out_file_xfm

        print '\n\n', self.inputs.out_file_xfm
        print self.inputs.out_file_xfm_invert
        print self.inputs.out_file_img, '\n\n'

        if self.inputs.verbose:
            print run_resample.cmdline
        if self.inputs.run:
            run_resample.run()

        #shutil.rmtree(tmpDir)
        return runtime
Exemple #7
0
def get_workflow(name, infosource, opts):
    '''
        Create workflow to perform PET to T1 co-registration.

        1. PET to T1 coregistration with brain masks
        2. Transform T1 MRI brainmask and headmask from MNI 152 to T1 native

        :param name: Name for workflow
        :param infosource: Infosource for basic variables like subject id (sid) and condition id (cid)
        :param datasink: Node in which output data is sent
        :param opts: User options

        :returns: workflow
    '''
    workflow = pe.Workflow(name=name)
    #bnDefine input node that will receive input from outside of workflow
    inputnode = pe.Node(niu.IdentityInterface(fields=[
        "pet_volume", "pet_volume_4d", "nativeT1nuc", "t1_headMask",
        "tka_label_img_t1", "results_label_img_t1", "pvc_label_img_t1",
        "t1_brain_mask", "xfmT1MNI", "T1Tal", "error", "header"
    ]),
                        name='inputnode')
    #Define empty node for output
    outputnode = pe.Node(niu.IdentityInterface(fields=[
        "petmri_img", "pet_img_4d", "petmri_xfm", "mripet_xfm", 'petmni_xfm',
        'mnipet_xfm'
    ]),
                         name='outputnode')

    node_name = "pet_brainmask"
    petMasking = pe.Node(interface=PETheadMasking(), name=node_name)
    petMasking.inputs.slice_factor = opts.slice_factor
    petMasking.inputs.total_factor = opts.total_factor
    workflow.connect(inputnode, 'pet_volume', petMasking, 'in_file')
    workflow.connect(inputnode, 'header', petMasking, 'in_json')

    node_name = "pet2mri"
    pet2mri = pe.Node(interface=PETtoT1LinRegRunning(), name=node_name)
    pet2mri.inputs.clobber = True
    pet2mri.inputs.verbose = opts.verbose
    pet2mri.inputs.lsq = "lsq6"
    pet2mri.inputs.metric = "mi"

    workflow.connect([
        (inputnode, pet2mri, [('pet_volume', 'in_source_file')]),
        (inputnode, pet2mri, [('nativeT1nuc', 'in_target_file')])  #,
    ])

    if opts.test_group_qc: misalign_pet(workflow, inputnode, pet2mri)

    PETMNIXfm_node = pe.Node(interface=ConcatCommand(), name="PETMNIXfm_node")
    workflow.connect(pet2mri, "out_file_xfm", PETMNIXfm_node, "in_file")
    workflow.connect(inputnode, "xfmT1MNI", PETMNIXfm_node, "in_file_2")

    MNIPETXfm_node = pe.Node(interface=minc.XfmInvert(), name="MNIPETXfm_node")
    workflow.connect(PETMNIXfm_node, "out_file", MNIPETXfm_node, 'input_file')

    workflow.connect(PETMNIXfm_node, 'out_file', outputnode, 'petmni_xfm')
    workflow.connect(MNIPETXfm_node, 'output_file', outputnode, 'mnipet_xfm')

    #Resample 4d PET image to T1 space
    if opts.analysis_space == 't1':
        pettot1_4d = pe.Node(interface=minc.Resample(), name='pet_t1_4d')
        pettot1_4d.inputs.keep_real_range = True
        workflow.connect(inputnode, 'pet_volume_4d', pettot1_4d, 'input_file')
        workflow.connect(pet2mri, 'out_file_xfm', pettot1_4d, 'transformation')
        workflow.connect(inputnode, 'nativeT1nuc', pettot1_4d, 'like')
        workflow.connect(pettot1_4d, 'output_file', outputnode, 'pet_img_4d')

        workflow.connect(inputnode, 'nativeT1nuc', outputnode,
                         't1_analysis_space')
    elif opts.analysis_space == "stereo":
        #Resample 4d PET image to MNI space
        pettomni_4d = pe.Node(interface=minc.Resample(), name='pet_mni_4d')
        pettomni_4d.inputs.keep_real_range = True
        workflow.connect(inputnode, 'pet_volume_4d', pettomni_4d, 'input_file')
        workflow.connect(PETMNIXfm_node, "out_file", pettomni_4d,
                         'transformation')
        workflow.connect(inputnode, 'T1Tal', pettomni_4d, 'like')
        workflow.connect(pettomni_4d, 'output_file', outputnode, 'pet_img_4d')

    workflow.connect(pet2mri, 'out_file_xfm', outputnode, 'petmri_xfm')
    workflow.connect(pet2mri, 'out_file_xfm_invert', outputnode, 'mripet_xfm')
    workflow.connect(pet2mri, 'out_file_img', outputnode, 'petmri_img')
    return workflow
def get_workflow(name, valid_args, opts):
    workflow = pe.Workflow(name=name)
    in_fields = ['t1']
    if opts.user_brainmask:
        in_fields += ['brain_mask_mni']

    if opts.user_t1mni:
        in_fields += ['xfmT1MNI']

    print("In Fields:", in_fields)
    label_types = [
        opts.tka_label_type, opts.pvc_label_type, opts.results_label_type
    ]
    stages = ['tka', 'pvc', 'results']
    label_imgs = [
        opts.tka_label_img[0], opts.results_label_img[0], opts.pvc_label_img[0]
    ]

    inputnode = pe.Node(niu.IdentityInterface(fields=in_fields),
                        name="inputnode")

    out_fields = [
        'xfmT1MNI', 'xfmT1MNI_invert', 'brain_mask_mni', 'brain_mask_t1',
        't1_mni'
    ]
    for stage, label_type in zip(stages, label_types):
        print(stage, label_type)
        if 'internal_cls' == label_type:
            out_fields += [stage + '_label_img']
            print(stage + '_label_img')

    outputnode = pe.Node(niu.IdentityInterface(fields=out_fields),
                         name='outputnode')

    if not opts.user_brainmask:
        if opts.beast_library_dir == None:
            library_dir = mincbeast_library(opts.template)
        else:
            library_dir = opts.beast_library_dir

        template_rsl = create_alt_template(opts.template, library_dir)

    #if not opts.user_brainmask :
    #    #Template Brain Mask
    #    template_brain_mask = pe.Node(interface=mincbeastCommand(), name="template_brain_mask")
    #    template_brain_mask.inputs.library_dir  = mincbeast_library(opts.template)
    #    template_brain_mask.inputs.configuration = template_brain_mask.inputs.library_dir+os.sep+"default.2mm.conf"
    #    template_brain_mask.inputs.in_file = opts.template
    #    template_brain_mask.inputs.same_resolution = True
    #    template_brain_mask.inputs.voxel_size = 2
    #    brain_mask_file = "out_file"
    #else :
    #    template_brain_mask = inputnode
    #    brain_mask_file = "brain_mask_mni"
    if not opts.user_t1mni:
        if opts.coreg_method == 'ants':
            mri2template = pe.Node(interface=mincANTSCommand(
                args='--float',
                collapse_output_transforms=True,
                fixed_image=opts.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-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="mincANTS_registration")

            mri2template.inputs.write_composite_transform = True
            #mri2template.inputs.interpolation=""
            workflow.connect(inputnode, 't1', mri2template, 'moving_image')
            #workflow.connect(template_brain_mask, brain_mask_file, mri2template, 'fixed_image_mask')

            t1_mni_file = 'warped_image'
            t1_mni_node = mri2template
            tfm_node = mri2template
            tfm_file = 'composite_transform'
        else:
            #mri2template = pe.Node(interface=PETtoT1LinRegRunning(), name="minctracc_registration")
            #mri2template = pe.Node(interface=beast_normalize(), name="minctracc_registration")
            mri2template = pe.Node(interface=beast_normalize_with_conversion(),
                                   name="mri_normalize")
            #mri2template.inputs.clobber = True
            #mri2template.inputs.verbose = opts.verbose
            template_name = os.path.splitext(os.path.basename(template_rsl))[0]
            template_dir = os.path.dirname(opts.template)
            #mri2template.inputs.in_target_file = opts.template
            mri2template.inputs.modelname = template_name
            mri2template.inputs.modeldir = template_dir
            #workflow.connect(inputnode, 't1', mri2template, 'in_source_file')
            workflow.connect(inputnode, 't1', mri2template, 'in_file')
            #workflow.connect(template_brain_mask, brain_mask_file, mri2template, 'in_target_mask')

            t1_mni_file = 'out_file_vol'
            t1_mni_node = mri2template
            tfm_node = mri2template
            tfm_file = 'out_file_xfm'

    else:
        transform_t1 = pe.Node(interface=minc.Resample(), name="transform_t1")
        transform_t1.inputs.two = True
        workflow.connect(inputnode, 't1', transform_t1, 'input_file')
        workflow.connect(inputnode, 'xfmT1MNI', transform_t1, 'transformation')
        transform_t1.inputs.like = opts.template

        t1_mni_node = transform_t1
        t1_mni_file = 'output_file'
        tfm_node = inputnode
        tfm_file = 'xfmT1MNI'

    if not opts.user_brainmask:
        #Brain Mask MNI-Space
        t1MNI_brain_mask = pe.Node(interface=mincbeast(),
                                   name="t1_mni_brain_mask")
        t1MNI_brain_mask.inputs.library_dir = library_dir
        t1MNI_brain_mask.inputs.configuration = t1MNI_brain_mask.inputs.library_dir + os.sep + "default.2mm.conf"
        t1MNI_brain_mask.inputs.same_resolution = True
        t1MNI_brain_mask.inputs.median = True
        t1MNI_brain_mask.inputs.fill = True

        workflow.connect(t1_mni_node, t1_mni_file, t1MNI_brain_mask, "in_file")

        brain_mask_node = t1MNI_brain_mask
        brain_mask_file = 'out_file'
    else:
        brain_mask_node = inputnode
        brain_mask_file = 'brain_mask_mni'

    transform_brain_mask = pe.Node(interface=minc.Resample(),
                                   name="transform_brain_mask")
    transform_brain_mask.inputs.nearest_neighbour_interpolation = True
    transform_brain_mask.inputs.invert_transformation = True
    workflow.connect(brain_mask_node, brain_mask_file, transform_brain_mask,
                     'input_file')
    workflow.connect(inputnode, 't1', transform_brain_mask, 'like')
    workflow.connect(tfm_node, tfm_file, transform_brain_mask,
                     'transformation')

    seg = None
    for stage, label_type, img in zip(stages, label_types, label_imgs):
        if 'antsAtropos' == img and seg == None:
            seg = pe.Node(interface=mincAtroposCommand(),
                          name="segmentation_ants")
            seg.inputs.dimension = 3
            seg.inputs.number_of_tissue_classes = 3  #... opts.
            seg.inputs.initialization = 'Otsu'

            workflow.connect(t1_mni_node, t1_mni_file, seg, 'intensity_images')
            #workflow.connect(inputnode,'t1' ,  seg, 'intensity_images' )
            #workflow.connect(transform_brain_mask, 'output_file',  seg, 'mask_image' )
            workflow.connect(brain_mask_node, brain_mask_file, seg,
                             'mask_image')

        if 'antsAtropos' == img:
            workflow.connect(seg, 'classified_image', outputnode,
                             stage + '_label_img')

    workflow.connect(brain_mask_node, brain_mask_file, outputnode,
                     'brain_mask_mni')
    workflow.connect(tfm_node, tfm_file, outputnode, 'xfmT1MNI')
    workflow.connect(transform_brain_mask, 'output_file', outputnode,
                     'brain_mask_t1')
    workflow.connect(t1_mni_node, t1_mni_file, outputnode, 't1_mni')
    return (workflow)
Exemple #9
0
    def _run_interface(self, runtime):

        self.inputs.out_file = self._gen_output(
            self.inputs.label_img, self._suffix + self.inputs.analysis_space)

        tmpDir = os.getcwd() + os.sep + 'tmp_label'  #tempfile.mkdtemp()
        os.mkdir(tmpDir)

        out_file_1 = temp_mask = tmpDir + "/mask.mnc"
        temp_mask_clean = tmpDir + "/mask_clean.mnc"

        # 1) Select Labels
        run_calc = minc.Calc(
        )  #Extract the desired label from the atlas using minccalc.
        run_calc.inputs.input_files = self.inputs.label_img  #The ANIMAL or CIVET classified atlas
        run_calc.inputs.output_file = temp_mask  #Output mask with desired label
        run_calc.inputs.expression = " || ".join([
            '(A[0] > ' + str(label) + '-0.1 && A[0] < ' + str(label) +
            '+ 0.1 )' for label in self.inputs.labels
        ]) + ' ? A[0] : 0'
        run_calc.run()
        print("Select Labels:\n", run_calc.cmdline)

        # 2) Erode
        if int(self.inputs.erode_times) > 0:
            run_mincmorph = MorphCommand()
            run_mincmorph.inputs.in_file = temp_mask
            run_mincmorph.inputs.out_file = temp_mask_clean
            run_mincmorph.inputs.successive = 'E' * self.inputs.erode_times
            run_mincmorph.run()
            out_file_1 = temp_mask_clean

        out_file_1 = self.inputs.out_file

        # 3) Co-registration
        if self.inputs.space == "stereo" and self.inputs.label_type == "atlas-template":
            if self.inputs.nLinAtlasMNIXfm == '':
                sourceToModel_xfm = os.getcwd() + os.sep + 'template2mni.xfm'
                run_nlinreg = reg.nLinRegRunning()
                run_nlinreg.inputs.in_source_file = self.inputs.label_template
                run_nlinreg.inputs.in_target_file = self.inputs.mniT1
                run_nlinreg.inputs.out_file_xfm = sourceToModel_xfm  # xfm file for the transformation from template to subject stereotaxic
                run_nlinreg.run()

                mni2target = minc.XfmConcat()
                mni2target.inputs.input_file_1 = sourceToModel_xfm
                mni2target.inputs.input_file_2 = self.inputs.mni2target
                mni2target.run()

                self.inputs.nLinAtlasMNIXfm = mni2target.inputs.output_file
            else:
                sourceToModel_xfm = self.inputs.nLinAtlasMNIXfm
        else:
            xfm = self.inputs.LinXfm

        # 4) Apply transformation
        like_file = self.inputs.like_file
        base = splitext(out_file_1)
        out_file_2 = base[0] + self.inputs.analysis_space + base[1]

        run_resample = minc.Resample()
        run_resample.inputs.input_file = self.inputs.label_img
        run_resample.inputs.output_file = out_file_2
        run_resample.inputs.like = like_file
        run_resample.inputs.transformation = xfm
        run_resample.inputs.nearest_neighbour_interpolation = True
        run_resample.run()

        #if self.inputs.space == "stereo" and self.inputs.label_type == "atlas-template":
        #    5) Resample 'other' atlas into T1 native space
        #    run_resample = minc.Resample()
        #    run_resample.inputs.input_file = out_file_2
        #    run_resample.inputs.output_file = self.inputs.LabelsT1
        #    run_resample.inputs.like = self.inputs.nativeT1
        #    run_resample.inputs.transformation = self.inputs.LinMNIT1Xfm
        #    run_resample.inputs.nearest_neighbour_interpolation = True
        #    print run_resample.cmdline
        #    run_resample.run()
        label = run_resample.inputs.output_file

        #Copy to output
        shutil.copy(label, self.inputs.out_file)
        #self.inputs.out_file = run_resample.inputs.output_file

        # 6) Mask brain for T1 and MNI labels
        if self.inputs.brain_only:
            temp_mask = tmpDir + "/mask.mnc"
            run_calc = minc.Calc(
            )  #Extract the desired label from the atlas using minccalc.
            run_calc.inputs.input_files = [label, self.inputs.brainmask]
            run_calc.inputs.output_file = temp_mask  #Output mask with desired label
            run_calc.inputs.expression = " A[1] == 1 ? A[0] : 0 "
            run_calc.clobber = True
            run_calc.run()
            #shutil.copy(temp_mask, label)
            shutil.copy(temp_mask, self.inputs.out_file)
            label = self.inputs.out_file
            print "Warning: masking labeled image with brain mask."
            print "Label: ", label
        if self.inputs.ones_only:
            temp_mask = tmpDir + "/mask.mnc"
            run_calc = minc.Calc(
            )  #Extract the desired label from the atlas using minccalc.
            run_calc.inputs.input_files = [
                label
            ]  #The ANIMAL or CIVET classified atlas
            run_calc.inputs.output_file = temp_mask  #Output mask with desired label
            run_calc.inputs.expression = " A[0] > 0.1 ? 1 : 0 "
            run_calc.clobber = True
            run_calc.run()
            #shutil.copy(temp_mask, label)
            shutil.copy(temp_mask, self.inputs.out_file)

        return runtime
Exemple #10
0
def get_workflow(name, infosource, opts):
    '''
        Create workflow to produce labeled images.

        1. Invert T1 Native to MNI 152 transformation
        2. Transform
        4. Transform brainmask from MNI 152 to T1 native
        5. Create PVC labeled image
        6. Create quantification labeled image
        7. Create results labeled image

        :param name: Name for workflow
        :param infosource: Infosource for basic variables like subject id (sid) and condition id (cid)
        :param datasink: Node in which output data is sent
        :param opts: User options
        
        :returns: workflow
    '''
    workflow = pe.Workflow(name=name)
    out_list = [
        "pet_brainmask", "brain_mask", "results_label_img_t1",
        "results_label_img_mni"
    ]
    in_list = [
        "nativeT1", "mniT1", "brainmask", "pet_header_json", "pet_volume",
        "results_labels", "results_label_template", "results_label_img",
        'LinT1MNIXfm', "LinPETMNIXfm", "LinMNIPETXfm", "LinT1PETXfm",
        "LinPETT1Xfm"
    ]
    if not opts.nopvc:
        out_list += ["pvc_label_img_t1", "pvc_label_img_mni"]
        in_list += [
            "pvc_labels", "pvc_label_space", "pvc_label_img",
            "pvc_label_template"
        ]
    if not opts.tka_method == None:
        out_list += ["tka_label_img_t1", "tka_label_img_mni"]
        in_list += [
            "tka_labels", "tka_label_space", "tka_label_template",
            "tka_label_img"
        ]
    #Define input node that will receive input from outside of workflow
    inputnode = pe.Node(niu.IdentityInterface(fields=in_list),
                        name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(fields=out_list),
                         name='outputnode')
    #Define empty node for output

    MNIT1 = pe.Node(interface=minc.XfmInvert(), name="MNIT1")
    workflow.connect(inputnode, 'LinT1MNIXfm', MNIT1, 'input_file')
    MNIPET = pe.Node(interface=minc.XfmInvert(), name="MNIPET")
    workflow.connect(inputnode, 'LinPETMNIXfm', MNIPET, 'input_file')

    if not opts.nopvc and not opts.pvc_method == None:
        pvc_tfm_node, pvc_tfm_file, pvc_tfm_to, pvc_target_file = get_transforms_for_stage(
            MNIT1, MNIPET, inputnode, opts.pvc_label_space,
            opts.analysis_space)

    if not opts.tka_method == None:
        tka_tfm_node, tka_tfm_file, tka_tfm_to, tka_target_file = get_transforms_for_stage(
            MNIT1, MNIPET, inputnode, opts.tka_label_space,
            opts.analysis_space)

    results_tfm_node, results_tfm_file, results_tfm_to, results_target_file = get_transforms_for_stage(
        MNIT1, MNIPET, inputnode, opts.results_label_space,
        opts.analysis_space)

    brain_mask_tfm_node, brain_mask_tfm_file, brain_mask_tfm_to, brain_mask_target_file = get_transforms_for_stage(
        MNIT1, MNIPET, inputnode, 'stereo', 'pet')
    ###################
    # Brain Mask Node #
    ###################
    if opts.analysis_space != "stereo":
        brain_mask_node = pe.Node(minc.Resample(), "brain_mask_node")
        brain_mask_node.inputs.nearest_neighbour_interpolation = True
        #brain_mask_node.inputs.output_file="brain_mask_space-"+opts.analysis_space+".mnc"

        workflow.connect(inputnode, "brainmask", brain_mask_node, "input_file")
        if opts.analysis_space == "t1":
            workflow.connect(MNIT1, "output_file", brain_mask_node,
                             "transformation")
            like_file = "nativeT1"
            workflow.connect(inputnode, "nativeT1", brain_mask_node, "like")
        elif opts.analysis_space == "pet":
            workflow.connect(MNIPET, "output_file", brain_mask_node,
                             "transformation")
            workflow.connect(inputnode, "pet_volume", brain_mask_node, "like")
            like_file = "pet_volume"
        else:
            print("Error: Analysis space must be one of pet,stereo,t1 but is",
                  opts.analysis_space)
            exit(1)
    else:
        brain_mask_node = pe.Node(
            niu.IdentityInterface(fields=["output_file"]), "brain_mask")
        workflow.connect(inputnode, "brainmask", brain_mask_node,
                         "output_file")
        like_file = "mniT1"

    resultsLabels = pe.Node(interface=Labels(), name="resultsLabels")
    resultsLabels.inputs.analysis_space = opts.analysis_space
    resultsLabels.inputs.label_type = opts.results_label_type
    resultsLabels.inputs.space = opts.results_label_space
    resultsLabels.inputs.erode_times = opts.results_erode_times
    resultsLabels.inputs.brain_only = opts.results_labels_brain_only
    resultsLabels.inputs.ones_only = opts.results_labels_ones_only
    workflow.connect(inputnode, 'results_labels', resultsLabels, 'labels')
    workflow.connect(inputnode, 'results_label_img', resultsLabels,
                     'label_img')
    workflow.connect(inputnode, 'results_label_template', resultsLabels,
                     'label_template')
    workflow.connect(inputnode, like_file, resultsLabels, 'like_file')
    workflow.connect(brain_mask_node, "output_file", resultsLabels,
                     'brainmask')
    workflow.connect(results_tfm_node, results_tfm_file, resultsLabels,
                     "LinXfm")

    if not opts.nopvc and not opts.pvc_method == None:
        pvcLabels = pe.Node(interface=Labels(), name="pvcLabels")
        pvcLabels.inputs.analysis_space = opts.analysis_space
        pvcLabels.inputs.label_type = opts.pvc_label_type
        pvcLabels.inputs.space = opts.pvc_label_space
        pvcLabels.inputs.erode_times = opts.pvc_erode_times
        pvcLabels.inputs.brain_only = opts.pvc_labels_brain_only
        pvcLabels.inputs.ones_only = opts.pvc_labels_ones_only
        workflow.connect(inputnode, 'pvc_labels', pvcLabels, 'labels')
        workflow.connect(inputnode, 'pvc_label_img', pvcLabels, 'label_img')
        workflow.connect(inputnode, 'pvc_label_template', pvcLabels,
                         'label_template')
        workflow.connect(inputnode, like_file, pvcLabels, 'like_file')
        workflow.connect(brain_mask_node, "output_file", pvcLabels,
                         'brainmask')
        workflow.connect(pvc_tfm_node, pvc_tfm_file, pvcLabels, "LinXfm")
    if not opts.tka_method == None:
        tkaLabels = pe.Node(interface=Labels(), name="tkaLabels")
        tkaLabels.inputs.analysis_space = opts.analysis_space
        tkaLabels.inputs.label_type = opts.tka_label_type
        tkaLabels.inputs.space = opts.tka_label_space
        tkaLabels.inputs.erode_times = opts.tka_erode_times
        tkaLabels.inputs.brain_only = opts.tka_labels_brain_only
        tkaLabels.inputs.ones_only = opts.tka_labels_ones_only
        workflow.connect(inputnode, 'tka_labels', tkaLabels, 'labels')
        workflow.connect(inputnode, 'tka_label_img', tkaLabels, 'label_img')
        workflow.connect(inputnode, 'tka_label_template', tkaLabels,
                         'label_template')
        workflow.connect(inputnode, like_file, tkaLabels, 'like_file')
        workflow.connect(brain_mask_node, "output_file", tkaLabels,
                         'brainmask')
        workflow.connect(tka_tfm_node, tka_tfm_file, tkaLabels, "LinXfm")

    #workflow.connect(brain_mask_node,"output_file", outputnode, 'brain_mask')
    return (workflow)
Exemple #11
0
def get_workflow(name, opts):
    workflow = pe.Workflow(name=name)
    in_fields = ['t1']
    if opts.user_brainmask :
        in_fields += ['brain_mask_mni']
    
    if opts.user_t1mni :
        in_fields += ['xfmT1MNI']

    print("In Fields:", in_fields)
    label_types = [opts.tka_label_type, opts.pvc_label_type, opts.results_label_type]
    stages = ['tka', 'pvc', 'results']
    label_imgs= [opts.tka_label_img, opts.results_label_img, opts.pvc_label_img ]

    inputnode = pe.Node(niu.IdentityInterface(fields=in_fields), name="inputnode")

    out_fields=['xfmMNIT1', 'xfmT1MNI',  'xfmT1MNI_invert',  'brain_mask_mni', 'brain_mask_t1', 't1_mni', 't1_nat' ]
    for stage, label_type in zip(stages, label_types):
        print( stage, label_type )
        if 'internal_cls' == label_type :
            out_fields += [ stage+'_label_img']
            print( stage+'_label_img' )
    
    outputnode = pe.Node(niu.IdentityInterface(fields=out_fields), name='outputnode')

    #
    # Setup dir for minc beast if not using user provided brain mask
    #
    if not opts.user_brainmask : 
        if opts.beast_library_dir == None :
            library_dir = mincbeast_library(opts.template)
        else :
            library_dir = opts.beast_library_dir
        
        template_rsl = create_alt_template(opts.template, library_dir)

    ##########################################
    # T1 spatial (+ intensity) normalization #
    ##########################################

    if not opts.user_t1mni:
        if opts.coreg_method == 'ants' :
            mri2template = pe.Node(interface=mincANTSCommand(args='--float',
                collapse_output_transforms=True,
                fixed_image=opts.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-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="mincANTS_registration")

            mri2template.inputs.write_composite_transform=True
            workflow.connect(inputnode, 't1', mri2template, 'moving_image')

            t1_mni_file = 'warped_image'
            t1_mni_node=mri2template
            tfm_node= mri2template
            tfm_file='composite_transform'
        else :
            mri2template = pe.Node(interface=beast_normalize_with_conversion(), name="mri_normalize")
            template_name = os.path.splitext(os.path.basename(template_rsl))[0]
            template_dir = os.path.dirname(opts.template)
            mri2template.inputs.modelname = template_name
            mri2template.inputs.modeldir = template_dir
            workflow.connect(inputnode, 't1', mri2template, 'in_file')

            t1_mni_file = 'out_file_vol'
            t1_mni_node=mri2template
            tfm_node= mri2template
            tfm_file='out_file_xfm'
    else :
        transform_t1 = pe.Node(interface=minc.Resample(), name="transform_t1"  )
        transform_t1.inputs.two=True
        workflow.connect(inputnode, 't1', transform_t1, 'input_file')
        workflow.connect(inputnode, 'xfmT1MNI', transform_t1, 'transformation')
        transform_t1.inputs.like = opts.template

        t1_mni_node = transform_t1
        t1_mni_file = 'output_file'
        tfm_node = inputnode
        tfm_file = 'xfmT1MNI'

    #
    # Invert transformation from T1 to MNI space
    #
    xfmMNIT1 = pe.Node(interface=minc.XfmInvert(), name="MNIT1")
    workflow.connect(tfm_node, tfm_file, xfmMNIT1 , 'input_file')

    #
    # T1 in native space will be part of the APPIAN target directory
    # and hence it won't be necessary to link to the T1 in the source directory.
    #
    copy_t1_nat = pe.Node(interface=copyCommand(), name="t1_nat"  )
    workflow.connect(inputnode, 't1', copy_t1_nat, 'input_file')

    ####################
    # T1 Brain masking #
    ####################
    if not opts.user_brainmask :
        #Brain Mask MNI-Space
        t1MNI_brain_mask = pe.Node(interface=mincbeast(), name="t1_mni_brain_mask")
        t1MNI_brain_mask.inputs.library_dir  = library_dir
        t1MNI_brain_mask.inputs.configuration = t1MNI_brain_mask.inputs.library_dir+os.sep+"default.2mm.conf"
        t1MNI_brain_mask.inputs.same_resolution = True
        t1MNI_brain_mask.inputs.median = True
        t1MNI_brain_mask.inputs.fill = True
        #t1MNI_brain_mask.inputs.voxel_size=opts.beast_voxel_size
        t1MNI_brain_mask.inputs.median = opts.beast_median

        workflow.connect(t1_mni_node, t1_mni_file, t1MNI_brain_mask, "in_file" )

        brain_mask_node = t1MNI_brain_mask
        brain_mask_file = 'out_file'
    else :			
        brain_mask_node = inputnode
        brain_mask_file = 'brain_mask_mni'
    #
    # Transform brain mask from stereotaxic to T1 native space
    #
    transform_brain_mask = pe.Node(interface=minc.Resample(), name="transform_brain_mask"  )
    transform_brain_mask.inputs.nearest_neighbour_interpolation = True
    transform_brain_mask.inputs.invert_transformation = True
    workflow.connect(brain_mask_node, brain_mask_file, transform_brain_mask, 'input_file')
    workflow.connect(inputnode, 't1', transform_brain_mask, 'like')
    workflow.connect(tfm_node, tfm_file, transform_brain_mask, 'transformation')


    ###################################
    # Segment T1 in Stereotaxic space #
    ###################################
    seg=None
    for stage, label_type, img in zip(stages, label_types, label_imgs) :
        print(img, seg)
        if 'antsAtropos' == img and seg == None :
            seg = pe.Node(interface=mincAtroposCommand(), name="segmentation_ants")
            seg.inputs.dimension=3
            seg.inputs.number_of_tissue_classes=3 #... opts.
            seg.inputs.initialization = 'Otsu'
            
            workflow.connect(t1_mni_node, t1_mni_file,  seg, 'intensity_images' )
            workflow.connect(brain_mask_node, brain_mask_file,  seg, 'mask_image' )
           
        if 'antsAtropos' == img :
           workflow.connect(seg, 'classified_image', outputnode, stage+'_label_img')
   
    ###############################
    # Pass results to output node #
    ###############################
    workflow.connect(brain_mask_node, brain_mask_file, outputnode, 'brain_mask_mni')
    workflow.connect(tfm_node, tfm_file, outputnode, 'xfmT1MNI' )
    workflow.connect(xfmMNIT1, 'output_file', outputnode, 'xfmMNIT1' )
    workflow.connect(transform_brain_mask, 'output_file', outputnode, 'brain_mask_t1')
    workflow.connect(t1_mni_node, t1_mni_file, outputnode, 't1_mni')
    workflow.connect(copy_t1_nat, 'output_file', outputnode, 't1_nat')
    return(workflow)
Exemple #12
0
    def _run_interface(self, runtime):
        self.inputs.out_file = self._gen_output(
            self.inputs.label_img, self._suffix + self.inputs.analysis_space)

        tmpDir = os.getcwd() + os.sep + 'tmp_label'  #tempfile.mkdtemp()
        os.mkdir(tmpDir)

        out_file_1 = temp_mask = tmpDir + "/mask.mnc"
        temp_mask_clean = tmpDir + "/mask_clean.mnc"
        if self.inputs.labels == []:
            mask = pyminc.volumeFromFile(self.inputs.label_img)
            mask_flat = mask.data.flatten()
            labels = [str(int(round(i))) for i in np.unique(mask_flat)]
            if '0' in labels: labels.remove('0')
        else:
            labels = self.inputs.labels
        # 1) Select Labels
        run_calc = minc.Calc(
        )  #Extract the desired label from the atlas using minccalc.
        run_calc.inputs.input_files = self.inputs.label_img  #The ANIMAL or CIVET classified atlas
        run_calc.inputs.output_file = temp_mask  #Output mask with desired label
        run_calc.inputs.expression = " || ".join([
            '(A[0] > ' + str(label) + '-0.1 && A[0] < ' + str(label) +
            '+ 0.1 )' for label in labels
        ]) + ' ? A[0] : 0'
        run_calc.run()

        # 2) Erode
        if int(self.inputs.erode_times) > 0:
            run_mincmorph = MorphCommand()
            run_mincmorph.inputs.in_file = temp_mask
            run_mincmorph.inputs.out_file = temp_mask_clean
            run_mincmorph.inputs.successive = 'E' * self.inputs.erode_times
            run_mincmorph.run()
            out_file_1 = temp_mask_clean
        else:
            out_file_1 = temp_mask  #self.inputs.out_file

        # 3) Co-registration
        if self.inputs.space == "stereo" and self.inputs.label_type == "atlas-template":
            if self.inputs.nLinAtlasMNIXfm == '':
                sourceToModel_xfm = os.getcwd() + os.sep + 'template2mni.xfm'
                run_nlinreg = reg.nLinRegRunning()
                run_nlinreg.inputs.in_source_file = self.inputs.label_template
                run_nlinreg.inputs.in_target_file = self.inputs.mniT1
                run_nlinreg.inputs.out_file_xfm = sourceToModel_xfm  # xfm file for the transformation from template to subject stereotaxic
                run_nlinreg.run()

                mni2target = minc.XfmConcat()
                mni2target.inputs.input_file_1 = sourceToModel_xfm
                mni2target.inputs.input_file_2 = self.inputs.mni2target
                mni2target.run()
                xfm = mni2target.inputs.out_file
                self.inputs.nLinAtlasMNIXfm = mni2target.inputs.output_file
            else:
                xfm = self.inputs.nLinAtlasMNIXfm
        else:
            xfm = self.inputs.LinXfm

        # 4) Apply transformation
        like_file = self.inputs.like_file
        base = splitext(out_file_1)
        out_file_2 = base[0] + self.inputs.analysis_space + base[1]

        run_resample = minc.Resample()
        run_resample.inputs.input_file = out_file_1  # self.inputs.label_img
        run_resample.inputs.output_file = out_file_2
        run_resample.inputs.like = like_file
        run_resample.inputs.transformation = xfm
        run_resample.inputs.nearest_neighbour_interpolation = True
        run_resample.run()

        label = run_resample.inputs.output_file

        #Copy to output
        shutil.copy(label, self.inputs.out_file)

        # 6) Mask brain for T1 and MNI labels
        if self.inputs.brain_only:
            temp_mask = tmpDir + "/mask.mnc"
            run_calc = minc.Calc(
            )  #Extract the desired label from the atlas using minccalc.
            run_calc.inputs.input_files = [label, self.inputs.brain_mask]
            run_calc.inputs.output_file = temp_mask  #Output mask with desired label
            run_calc.inputs.expression = " A[1] == 1 ? A[0] : 0 "
            run_calc.clobber = True
            run_calc.run()
            shutil.copy(temp_mask, self.inputs.out_file)
            label = self.inputs.out_file
        if self.inputs.ones_only:
            temp_mask = tmpDir + "/mask.mnc"
            run_calc = minc.Calc(
            )  #Extract the desired label from the atlas using minccalc.
            run_calc.inputs.input_files = [
                label
            ]  #The ANIMAL or CIVET classified atlas
            run_calc.inputs.output_file = temp_mask  #Output mask with desired label
            run_calc.inputs.expression = " A[0] > 0.1 ? 1 : 0 "
            run_calc.clobber = True
            run_calc.run()
            shutil.copy(temp_mask, self.inputs.out_file)

        return runtime
Exemple #13
0
def get_workflow(name, infosource, opts):
    '''
        Create workflow to produce labeled images.

        1. Invert T1 Native to MNI 152 transformation
        2. Transform
        4. Transform brain_mask from MNI 152 to T1 native
        5. Create PVC labeled image
        6. Create quantification labeled image
        7. Create results labeled image

        :param name: Name for workflow
        :param infosource: Infosource for basic variables like subject id (sid) and condition id (cid)
        :param datasink: Node in which output data is sent
        :param opts: User options

        :returns: workflow
    '''
    workflow = pe.Workflow(name=name)
    out_list = [
        "pet_brain_mask", "brain_mask", "results_label_img_t1",
        "results_label_img_mni"
    ]
    in_list = [
        "nativeT1", "mniT1", "brain_mask_stereo", "brain_mask_t1",
        "pet_header_json", "pet_volume", "results_labels",
        "results_label_template", "results_label_img", 'LinT1MNIXfm',
        'LinMNIT1Xfm', "LinPETMNIXfm", "LinMNIPETXfm", 'LinT1MNIXfm',
        "LinT1PETXfm", "LinPETT1Xfm", "surf_left", 'surf_right'
    ]
    if not opts.pvc_method == None:
        out_list += ["pvc_label_img_t1", "pvc_label_img_mni"]
        in_list += [
            "pvc_labels", "pvc_label_space", "pvc_label_img",
            "pvc_label_template"
        ]
    if not opts.tka_method == None:
        out_list += ["tka_label_img_t1", "tka_label_img_mni"]
        in_list += [
            "tka_labels", "tka_label_space", "tka_label_template",
            "tka_label_img"
        ]
    #Define input node that will receive input from outside of workflow
    inputnode = pe.Node(niu.IdentityInterface(fields=in_list),
                        name='inputnode')
    outputnode = pe.Node(niu.IdentityInterface(fields=out_list),
                         name='outputnode')
    #Define empty node for output

    #Create Identity Transform
    identity_transform = pe.Node(param2xfmCommand(), name="identity_transform")
    identity_transform.inputs.translation = "0 0 0"
    identity_transform.inputs.rotation = "0 0 0"
    identity_transform.inputs.scales = "1 1 1"

    if not opts.pvc_method == None and not opts.pvc_method == None:
        pvc_tfm_node, pvc_tfm_file, pvc_target_file = get_transforms_for_stage(
            inputnode, opts.pvc_label_space, opts.analysis_space,
            identity_transform)

    if not opts.tka_method == None:
        tka_tfm_node, tka_tfm_file, tka_target_file = get_transforms_for_stage(
            inputnode, opts.tka_label_space, opts.analysis_space,
            identity_transform)

    results_tfm_node, results_tfm_file, results_target_file = get_transforms_for_stage(
        inputnode, opts.results_label_space, opts.analysis_space,
        identity_transform)

    ###################
    # Brain Mask Node #
    ###################
    if opts.analysis_space == "stereo":
        brain_mask_node = pe.Node(
            niu.IdentityInterface(fields=["output_file"]), "brain_mask")
        workflow.connect(inputnode, "brain_mask_stereo", brain_mask_node,
                         "output_file")
        like_file = "mniT1"
    elif opts.analysis_space == "t1":
        brain_mask_node = pe.Node(
            niu.IdentityInterface(fields=["output_file"]), "brain_mask")
        workflow.connect(inputnode, "brain_mask_t1", brain_mask_node,
                         "output_file")
        like_file = "nativeT1"
    elif opts.analysis_space == "pet":
        brain_mask_node = pe.Node(minc.Resample(), "brain_mask")
        brain_mask_node.inputs.nearest_neighbour_interpolation = True
        workflow.connect(inputnode, "brain_mask_stereo", brain_mask_node,
                         "input_file")
        workflow.connect(inputnode, "LinMNIPETXfm", brain_mask_node,
                         "transformation")
        workflow.connect(inputnode, "pet_volume", brain_mask_node, "like")
        like_file = "pet_volume"
    else:
        print("Error: Analysis space must be one of pet,stereo,t1 but is",
              opts.analysis_space)
        exit(1)

    #################
    # Surface masks #
    #################
    if opts.use_surfaces:
        if opts.analysis_space != "stereo":
            surface_left_node = pe.Node(transform_objectCommand(),
                                        name="surface_left_node")
            surface_right_node = pe.Node(transform_objectCommand(),
                                         name="surface_right_node")
            workflow.connect(inputnode, 'surf_left', surface_left_node,
                             'in_file')
            workflow.connect(inputnode, 'surf_right', surface_right_node,
                             'in_file')
            if opts.analysis_space == "t1":
                workflow.connect(inputnode, "LinMNIT1Xfm", surface_left_node,
                                 'tfm_file')
                workflow.connect(inputnode, "LinMNIT1Xfm", surface_right_node,
                                 'tfm_file')
            elif opts.analysis_space == "pet":
                workflow.connect(inputnode, 'LinMNIPETXfm', surface_left_node,
                                 'tfm_file')
                workflow.connect(inputnode, 'LinMNIPETXfm', surface_right_node,
                                 'tfm_file')
        else:
            surface_left_node = pe.Node(
                niu.IdentityInterface(fields=["output_file"]),
                "surf_left_node")
            surface_right_node = pe.Node(
                niu.IdentityInterface(fields=["output_file"]),
                "surf_right_node")
            workflow.connect(inputnode, "surf_left", surface_left_node,
                             "output_file")
            workflow.connect(inputnode, "surf_right", surface_right_node,
                             "output_file")

    resultsLabels = pe.Node(interface=Labels(), name="resultsLabels")
    resultsLabels.inputs.analysis_space = opts.analysis_space
    resultsLabels.inputs.label_type = opts.results_label_type
    resultsLabels.inputs.space = opts.results_label_space
    resultsLabels.inputs.erode_times = opts.results_erode_times
    resultsLabels.inputs.brain_only = opts.results_labels_brain_only
    resultsLabels.inputs.ones_only = opts.results_labels_ones_only
    workflow.connect(inputnode, 'results_labels', resultsLabels, 'labels')
    workflow.connect(inputnode, 'results_label_img', resultsLabels,
                     'label_img')
    workflow.connect(inputnode, 'results_label_template', resultsLabels,
                     'label_template')
    workflow.connect(inputnode, like_file, resultsLabels, 'like_file')
    workflow.connect(brain_mask_node, "output_file", resultsLabels,
                     'brain_mask')
    workflow.connect(results_tfm_node, results_tfm_file, resultsLabels,
                     "LinXfm")

    #Setup node for nonlinear alignment of results template to default (icbm152) template
    if opts.results_label_template != None:
        results_template_norm = pe.Node(interface=reg.nLinRegRunning(),
                                        name="results_template_normalization")
        results_template_norm.inputs.in_target_file = opts.template
        results_template_norm.inputs.in_source_file = opts.results_label_template

        results_template_analysis_space = pe.Node(
            ConcatNLCommand(), name="results_template_analysis_space")
        workflow.connect(results_template_norm, 'out_file_xfm',
                         results_template_analysis_space, 'in_file')
        workflow.connect(results_template_norm, 'out_file_warp',
                         results_template_analysis_space, 'in_warp')
        workflow.connect(results_tfm_node, results_tfm_file,
                         results_template_analysis_space, 'in_file_2')

        workflow.connect(results_template_analysis_space, 'out_file',
                         resultsLabels, 'nLinAtlasMNIXfm')
        workflow.connect(results_template_analysis_space, 'out_warp',
                         resultsLabels, 'warp')
        workflow.connect(results_template_norm, 'out_file_img', resultsLabels,
                         'template')

    if not opts.pvc_method == None and not opts.pvc_method == None:
        pvcLabels = pe.Node(interface=Labels(), name="pvcLabels")
        pvcLabels.inputs.analysis_space = opts.analysis_space
        pvcLabels.inputs.label_type = opts.pvc_label_type
        pvcLabels.inputs.space = opts.pvc_label_space
        pvcLabels.inputs.erode_times = opts.pvc_erode_times
        pvcLabels.inputs.brain_only = opts.pvc_labels_brain_only
        pvcLabels.inputs.ones_only = opts.pvc_labels_ones_only
        workflow.connect(inputnode, 'pvc_labels', pvcLabels, 'labels')
        workflow.connect(inputnode, 'pvc_label_img', pvcLabels, 'label_img')
        workflow.connect(inputnode, like_file, pvcLabels, 'like_file')
        workflow.connect(brain_mask_node, "output_file", pvcLabels,
                         'brain_mask')
        workflow.connect(pvc_tfm_node, pvc_tfm_file, pvcLabels, "LinXfm")

        if opts.pvc_label_template != None:
            pvc_template_norm = pe.Node(interface=reg.nLinRegRunning(),
                                        name="pvc_template_normalization")
            pvc_template_norm.inputs.in_target_file = opts.template
            pvc_template_norm.inputs.in_source_file = opts.pvc_label_template

            pvc_template_analysis_space = pe.Node(
                ConcatNLCommand(), name="pvc_template_analysis_space")
            workflow.connect(pvc_template_norm, 'out_file_xfm',
                             pvc_template_analysis_space, 'in_file')
            workflow.connect(pvc_template_norm, 'out_file_warp',
                             pvc_template_analysis_space, 'in_warp')
            workflow.connect(pvc_tfm_node, pvc_tfm_file,
                             pvc_template_analysis_space, 'in_file_2')

            workflow.connect(pvc_template_analysis_space, 'out_file',
                             pvcLabels, 'nLinAtlasMNIXfm')
            workflow.connect(pvc_template_analysis_space, 'out_warp',
                             pvcLabels, 'warp')
            workflow.connect(pvc_template_norm, 'out_file_img', pvcLabels,
                             'template')

    if not opts.tka_method == None:
        tkaLabels = pe.Node(interface=Labels(), name="tkaLabels")
        tkaLabels.inputs.analysis_space = opts.analysis_space
        tkaLabels.inputs.label_type = opts.tka_label_type
        tkaLabels.inputs.space = opts.tka_label_space
        tkaLabels.inputs.erode_times = opts.tka_erode_times
        tkaLabels.inputs.brain_only = opts.tka_labels_brain_only
        tkaLabels.inputs.ones_only = opts.tka_labels_ones_only
        workflow.connect(inputnode, 'tka_labels', tkaLabels, 'labels')
        workflow.connect(inputnode, 'tka_label_img', tkaLabels, 'label_img')
        workflow.connect(inputnode, like_file, tkaLabels, 'like_file')
        workflow.connect(brain_mask_node, "output_file", tkaLabels,
                         'brain_mask')
        workflow.connect(tka_tfm_node, tka_tfm_file, tkaLabels, "LinXfm")

        if opts.tka_label_template != None:
            tka_template_norm = pe.Node(interface=reg.nLinRegRunning(),
                                        name="tka_template_normalization")
            tka_template_norm.inputs.in_source_file = opts.template
            tka_template_norm.inputs.in_target_file = opts.tka_label_template

            tka_template_analysis_space = pe.Node(
                ConcatNLCommand(), name="tka_template_analysis_space")
            workflow.connect(tka_template_norm, 'out_file_xfm',
                             tka_template_analysis_space, 'in_file')
            workflow.connect(tka_template_norm, 'out_file_warp',
                             tka_template_analysis_space, 'in_warp')
            workflow.connect(tka_tfm_node, tka_tfm_file,
                             tka_template_analysis_space, 'in_file_2')

            workflow.connect(tka_template_analysis_space, 'out_file',
                             tkaLabels, 'nLinAtlasMNIXfm')
            workflow.connect(tka_template_analysis_space, 'out_warp',
                             tkaLabels, 'warp')
            workflow.connect(tka_template_norm, 'out_file_img', tkaLabels,
                             'template')

    return (workflow)