Exemple #1
0
def misalign_pet(workflow, inputnode, pet2mri):
    ###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')

    ###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')

    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")
    t1_brain_mask_img = 'out_file'
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_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 #4
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
Exemple #5
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 #6
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)