Exemple #1
0
    def __init__(
            self,
            inSource,
            inTarget,
            output=None,  # ability to specify output transform when using strings for input
            logFile=None,
            maskFile=None,
            defaultDir="transforms",
            blur=0.56,
            resample_step=4,
            registration_step=10,
            w_translations=8,
            rotational_range=50,
            rotational_interval=10,
            mousedata=False):

        CmdStage.__init__(self,
                          None)  #don't do any arg processing in superclass
        # handling of the input files
        try:
            if rf.isFileHandler(inSource, inTarget):
                self.source = inSource.getBlur(fwhm=blur)
                self.target = inTarget.getBlur(fwhm=blur)
                if (output == None):
                    self.output = inSource.registerVolume(inTarget, defaultDir)
                else:
                    self.output = output
                if (logFile == None):
                    self.logFile = fh.logFromFile(inSource.logDir, self.output)
                else:
                    self.logFile = logFile
            else:
                # TODO: fix this to work with string input files
                self.source = inSource
                self.target = inTarget
        except:
            print "Failed in putting together RotationalMinctracc command; unexpected error:"
            raise

        # The resolution is used to determine the step size and
        # blurring kernels for the rotational minctracc call. This
        # should be based on the target, not the input file (source)
        highestResolution = rf.returnFinestResolution(inTarget)

        # TODO: finish the following if clause... hahaha
        #if(mousedata):

        self.addDefaults(resample_step * highestResolution,
                         registration_step * highestResolution,
                         w_translations * highestResolution,
                         int(rotational_range), int(rotational_interval))
        # potentially add a mask to the command
        self.finalizeCommand(inTarget, maskFile)
        self.setName()
        self.colour = "green"
Exemple #2
0
 def __init__(self, 
              inSource, 
              inTarget,
              output = None, # ability to specify output transform when using strings for input
              logFile = None,
              maskFile = None,
              defaultDir="transforms",
              blur=0.56,
              resample_step=4,
              registration_step=10,
              w_translations=8,
              rotational_range=50,
              rotational_interval=10,
              mousedata=False):
     
     CmdStage.__init__(self, None) #don't do any arg processing in superclass
     # handling of the input files
     try: 
         if rf.isFileHandler(inSource, inTarget):
             self.source = inSource.getBlur(fwhm=blur)
             self.target = inTarget.getBlur(fwhm=blur)  
             if(output == None):
                 self.output = inSource.registerVolume(inTarget, defaultDir)
             else:
                 self.output = output
             if(logFile == None):
                 self.logFile = fh.logFromFile(inSource.logDir, self.output)
             else:
                 self.logFile = logFile
         else:
             # TODO: fix this to work with string input files
             self.source = inSource
             self.target = inTarget
     except:
         print "Failed in putting together RotationalMinctracc command."
         print "Unexpected error: ", sys.exc_info()
         raise
     
     highestResolution = rf.getFinestResolution(inSource)
     
     # TODO: finish the following if clause... hahaha
     #if(mousedata):
         
     
     self.addDefaults(resample_step     * highestResolution,
                   registration_step * highestResolution,
                   w_translations    * highestResolution,
                   int(rotational_range),
                   int(rotational_interval))
     # potentially add a mask to the command
     self.finalizeCommand(inTarget, maskFile)
     self.setName()
     self.colour = "green"
Exemple #3
0
    def __init__(self, 
                 inFile, 
                 fwhm, 
                 defaultDir="tmp",
                 gradient=False):
        """calls mincblur with the specified 3D Gaussian kernel

        The inputs can be in one of two styles. The first argument can
        be an instance of RegistrationPipeFH, in which case the last
        volume in that instance (i.e. inFile.lastBasevol) will be
        blurred and the output will be determined by its blurFile
        method. Alternately, the inFile can be a string representing a
        filename, in which case the output and logfile will be set based on 
        the inFile name. If the fwhm specified is -1, we do not construct 
        a command.

        """
        
        if fwhm == -1:
            return
        
        CmdStage.__init__(self, None)
        try:
            if isFileHandler(inFile):
                blurlist = inFile.blurFile(fwhm, gradient, defaultDir)
                self.base = blurlist["base"]
                self.inputFiles = [inFile.getLastBasevol()]
                self.outputFiles = [blurlist["file"]]
                self.logFile = blurlist["log"]
                self.name = "mincblur " + str(fwhm) + " " + inFile.basename
                if gradient:
                    self.outputFiles.append(blurlist["gradient"])
            else:
                self.base = str(inFile).replace(".mnc", "")
                self.inputFiles = [inFile]
                blurBase = "".join([self.base, "_fwhm", str(fwhm), "_blur"])
                output = "".join([blurBase, ".mnc"])
                self.outputFiles = [output]
                self.logFile = fh.logFromFile(abspath(curdir), output)
                self.name = "mincblur " + str(fwhm) + " " + basename(inFile)
                if gradient:
                    gradientBase = blurBase.replace("blur", "dxyz")
                    self.outputFiles += ["".join([gradientBase, ".mnc"])] 
        except:
            print "Failed in putting together blur command."
            print "Unexpected error: ", sys.exc_info()
            
        self.cmd = ["mincblur", "-clobber", "-no_apodize", "-fwhm", str(fwhm),
                    self.inputFiles[0], self.base]
        if gradient:
            self.cmd += ["-gradient"]       
        self.colour="blue"
Exemple #4
0
    def __init__(self, inFile, fwhm, defaultDir="tmp", gradient=False):
        """calls mincblur with the specified 3D Gaussian kernel

        The inputs can be in one of two styles. The first argument can
        be an instance of RegistrationPipeFH, in which case the last
        volume in that instance (i.e. inFile.lastBasevol) will be
        blurred and the output will be determined by its blurFile
        method. Alternately, the inFile can be a string representing a
        filename, in which case the output and logfile will be set based on 
        the inFile name. If the fwhm specified is -1, we do not construct 
        a command.

        """

        if fwhm == -1:
            return

        CmdStage.__init__(self, None)
        try:
            if isFileHandler(inFile):
                blurlist = inFile.blurFile(fwhm, gradient, defaultDir)
                self.base = blurlist["base"]
                self.inputFiles = [inFile.getLastBasevol()]
                self.outputFiles = [blurlist["file"]]
                self.logFile = blurlist["log"]
                self.name = "mincblur " + str(fwhm) + " " + inFile.basename
                if gradient:
                    self.outputFiles.append(blurlist["gradient"])
            else:
                self.base = str(inFile).replace(".mnc", "")
                self.inputFiles = [inFile]
                blurBase = "".join([self.base, "_fwhm", str(fwhm), "_blur"])
                output = "".join([blurBase, ".mnc"])
                self.outputFiles = [output]
                self.logFile = fh.logFromFile(abspath(curdir), output)
                self.name = "mincblur " + str(fwhm) + " " + basename(inFile)
                if gradient:
                    gradientBase = blurBase.replace("blur", "dxyz")
                    self.outputFiles += ["".join([gradientBase, ".mnc"])]
        except:
            print "Failed in putting together blur command."
            print "Unexpected error: ", sys.exc_info()

        self.cmd = [
            "mincblur", "-clobber", "-no_apodize", "-fwhm",
            str(fwhm), self.inputFiles[0], self.base
        ]
        if gradient:
            self.cmd += ["-gradient"]
        self.colour = "blue"
Exemple #5
0
    def __init__(self, inputFiles, outputFile, logFile=None):
        CmdStage.__init__(self, None)

        # in case there is a single input file... (it's actually possible)
        if (not (type(inputFiles) is list)):
            inputFiles = [inputFiles]

        self.inputFiles = inputFiles
        self.outputFiles = [outputFile]
        self.logFile = logFile
        self.cmd = ["xfmconcat", "-clobber"]
        self.cmd += inputFiles
        self.cmd += [outputFile]
        self.name = "xfm-concat"
        self.colour = "yellow"
Exemple #6
0
 def __init__(self, 
              inputFiles,
              outputFile,
              logFile=None):
     CmdStage.__init__(self, None)
     
     # in case there is a single input file... (it's actually possible)
     if(not(type(inputFiles) is list)):
         inputFiles = [inputFiles]
     
     self.inputFiles = inputFiles
     self.outputFiles = [outputFile]
     self.logFile = logFile
     self.cmd = ["xfmconcat", "-clobber"]
     self.cmd += inputFiles
     self.cmd += [outputFile]
     self.name   = "xfm-concat"
     self.colour = "yellow"
Exemple #7
0
 def __init__(self, inputFH, outputFH, transform, defaultDir="tmp"):
     CmdStage.__init__(self, None)
     try:  
         if isFileHandler(inputFH, outputFH):
             self.inFile = inputFH.getLastBasevol()  
             self.xfm = transform
             self.outfile = createOutputFileName(outputFH, self.xfm, defaultDir, "_displacement.mnc")
             self.logFile = fh.logFromFile(outputFH.logDir, self.outfile)
         else:
             print ("minc_displacement only works using file handlers. "
                    "Exception being raised.")
             raise
 
     except:
         print "Failed in putting together minc_displacement command"
         print "Unexpected error: ", sys.exc_info()
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #8
0
 def __init__(self, inputFH, outputFH, transform, defaultDir="tmp"):
     CmdStage.__init__(self, None)
     try:  
         if isFileHandler(inputFH, outputFH):
             self.inFile = inputFH.getLastBasevol()  
             self.xfm = transform
             self.outfile = createOutputFileName(outputFH, self.xfm, defaultDir, "_displacement.mnc")
             self.logFile = fh.logFromFile(outputFH.logDir, self.outfile)
         else:
             print ("minc_displacement only works using file handlers. "
                    "Exception being raised.")
             raise
 
     except:
         print("Failed in putting together minc_displacement command")
         print("Unexpected error: ", sys.exc_info())
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #9
0
 def __init__(self, inputFH, targetFH, defaultDir="transforms"):
     CmdStage.__init__(self, None)
     
     try:  
         if isFileHandler(inputFH, targetFH):
             self.inFile = inputFH.getLastBasevol()  
             self.mask = inputFH.getMask() 
             self.xfm = inputFH.getLastXfm(targetFH)     
             self.outfile = self.setOutputFile(inputFH, defaultDir)
             self.logFile = fh.logFromFile(inputFH.logDir, self.outfile)
         else:
             print ("linear part of nlin currently only works using file handlers. "
                    "Exception being raised.")
             raise
 
     except:
         print "Failed in putting together linearPartofNlin command"
         print "Unexpected error: ", sys.exc_info()
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #10
0
 def __init__(self, inputFH, targetFH, defaultDir="transforms"):
     CmdStage.__init__(self, None)
     
     try:  
         if isFileHandler(inputFH, targetFH):
             self.inFile = inputFH.getLastBasevol()  
             self.mask = inputFH.getMask() 
             self.xfm = inputFH.getLastXfm(targetFH)     
             self.outfile = self.setOutputFile(inputFH, defaultDir)
             self.logFile = fh.logFromFile(inputFH.logDir, self.outfile)
         else:
             print ("linear part of nlin currently only works using file handlers. "
                    "Exception being raised.")
             raise
 
     except:
         print("Failed in putting together linearPartofNlin command")
         print("Unexpected error: ", sys.exc_info())
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #11
0
    def __init__(self, xfm, FH=None, logFile=None):
        CmdStage.__init__(self, None)

        try:
            self.xfm = xfm
            if isFileHandler(FH):
                invXfmBase = fh.removeBaseAndExtension(
                    self.xfm).split(".xfm")[0]
                self.output = fh.createBaseName(FH.transformsDir,
                                                invXfmBase + "_inverted.xfm")
                self.logFile = fh.logFromFile(FH.logDir, self.output)
            else:
                invXfmBase = splitext(self.xfm)[0]
                self.output = invXfmBase + "_inverted.xfm"
                if logFile:
                    self.logFile = logFile

        except:
            print "Failed in putting together xfminvert command"
            print "Unexpected error: ", sys.exc_info()

        self.finalizeCommand()
        self.setName()
Exemple #12
0
 def __init__(self, 
              resolution, 
              inFile,
              output=None,
              logFile=None,
              defaultDir="resampled"):
     
     """Resamples the input file to the resolution specified
        using autocrop. The -resample flag forces the use of
        mincresample.
        
        Resolutions should be specified in mm. 
        e.g. 56 microns should be specified as 0.056    
     """
        
     CmdStage.__init__(self, None)
     self.resolution = str(resolution)
     try:  
         if isFileHandler(inFile):
             self.inFile = inFile.getLastBasevol()               
             self.outfile = self.setOutputFile(inFile, defaultDir)
             self.logFile = fh.logFromFile(inFile.logDir, self.outfile)
         else:
             self.inFile = inFile
             self.outfile = output
             if not logFile:
                 self.logFile = fh.logFromFile(abspath(curdir), output)
             else:
                 self.logFile = logFile
 
     except:
         print "Failed in putting together autocrop command"
         print "Unexpected error: ", sys.exc_info()
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #13
0
 def __init__(self, 
              xfm,
              FH=None,
              logFile=None):
     CmdStage.__init__(self, None)
     
     try:  
         self.xfm = xfm
         if isFileHandler(FH):
             invXfmBase = fh.removeBaseAndExtension(self.xfm).split(".xfm")[0]
             self.output = fh.createBaseName(FH.transformsDir, invXfmBase + "_inverted.xfm")
             self.logFile = fh.logFromFile(FH.logDir, self.output)
         else:
             invXfmBase = splitext(self.xfm)[0]
             self.output = invXfmBase + "_inverted.xfm"
             if logFile:
                 self.logFile = logFile
 
     except:
         print "Failed in putting together xfminvert command"
         print "Unexpected error: ", sys.exc_info()
                                            
     self.finalizeCommand()
     self.setName()
Exemple #14
0
 def __init__(self, 
              inputArray, 
              outputAvg,
              output=None, 
              logFile=None, 
              defaultDir="tmp"):
     CmdStage.__init__(self, None)
     
     try:  
         """If output is fileHandler, we assume input array is as well"""
         if isFileHandler(outputAvg):
             self.filesToAvg = []
             for i in range(len(inputArray)):
                 self.filesToAvg.append(inputArray[i].getLastBasevol()) 
             """If no output file is specified, create default, using file handler
                otherwise use what is specified."""              
             if not output:
                 self.output = self.setOutputFile(outputAvg, defaultDir)
             else:
                 self.output = output
             self.logFile = fh.logFromFile(outputAvg.logDir, self.output)
         else:
             self.filesToAvg = inputArray
             self.output = outputAvg
             if not logFile:
                 self.logFile = fh.logFromFile(abspath(curdir), outputAvg)
             else:
                 self.logFile = logFile
 
     except:
         print "Failed in putting together mincaverage command"
         print "Unexpected error: ", sys.exc_info()
         
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
Exemple #15
0
    def __init__(self,
                 resolution,
                 inFile,
                 output=None,
                 logFile=None,
                 defaultDir="resampled"):
        """Resamples the input file to the resolution specified
           using autocrop. The -resample flag forces the use of
           mincresample.
           
           Resolutions should be specified in mm. 
           e.g. 56 microns should be specified as 0.056    
        """

        CmdStage.__init__(self, None)
        self.resolution = str(resolution)
        try:
            if isFileHandler(inFile):
                self.inFile = inFile.getLastBasevol()
                self.outfile = self.setOutputFile(inFile, defaultDir)
                self.logFile = fh.logFromFile(inFile.logDir, self.outfile)
            else:
                self.inFile = inFile
                self.outfile = output
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), output)
                else:
                    self.logFile = logFile

        except:
            print "Failed in putting together autocrop command"
            print "Unexpected error: ", sys.exc_info()

        self.addDefaults()
        self.finalizeCommand()
        self.setName()
Exemple #16
0
    def __init__(self,
                 inputArray,
                 outputAvg,
                 output=None,
                 logFile=None,
                 defaultDir="tmp"):
        CmdStage.__init__(self, None)

        try:
            """If output is fileHandler, we assume input array is as well"""
            if isFileHandler(outputAvg):
                self.filesToAvg = []
                for i in range(len(inputArray)):
                    self.filesToAvg.append(inputArray[i].getLastBasevol())
                """If no output file is specified, create default, using file handler
                   otherwise use what is specified."""
                if not output:
                    self.output = self.setOutputFile(outputAvg, defaultDir)
                else:
                    self.output = output
                self.logFile = fh.logFromFile(outputAvg.logDir, self.output)
            else:
                self.filesToAvg = inputArray
                self.output = outputAvg
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), outputAvg)
                else:
                    self.logFile = logFile

        except:
            print "Failed in putting together mincaverage command"
            print "Unexpected error: ", sys.exc_info()

        self.addDefaults()
        self.finalizeCommand()
        self.setName()
Exemple #17
0
    def __init__(self, 
                 inSource,
                 inTarget,
                 output=None,
                 logFile=None,
                 defaultDir="transforms", 
                 blur=None,
                 gradient=False,
                 linearparam="nlin",
                 source_mask=None, 
                 target_mask=None,
                 iterations=40,
                 step=0.5,
                 transform=None,
                 weight=0.8,
                 stiffness=0.98,
                 similarity=0.8,
                 w_translations=0.4,
                 w_rotations=0.0174533,
                 w_scales=0.02,
                 w_shear=0.02,
                 simplex=1,
                 optimization="-use_simplex",
                 useMask=True):
        #MF TODO: Specify different w_translations, rotations, scales shear in each direction?
        # Now assumes same in all directions
        # Go to more general **kwargs?
        
        """an efficient way to add a minctracc call to a pipeline

        The constructor needs two inputFile arguments, the source and the
        target for the registration, and multiple optional arguments
        for specifying parameters. The source and the target can be
        specified as either RegistrationPipeFH instances or as strings
        representing filenames. In the latter case an output and a
        logfile filename are required as well (these are filled in
        automatically in the case of RegistrationPipeFH instances.)

        """
        CmdStage.__init__(self, None) #don't do any arg processing in superclass
        try: 
            if isFileHandler(inSource, inTarget):
                """ if blur = None, getBlur returns lastblur
                if gradient is true, getBlur returns gradient instead of blur 
                if blur = -1, lastBaseVol is returned and gradient is ignored.
                
                self.transform will be None if there is no previous transform
                between input and target. If this is the case, lsq6 and lsq12
                defaults are added in the setTransforms function
                """
                self.source = inSource.getBlur(blur, gradient)
                self.target = inTarget.getBlur(blur, gradient)
                self.transform = inSource.getLastXfm(inTarget)
                """If no output transform is specified, use registerVolume to create a default.
                   If an output transform name is specified, use this as the output, and add it as the last xfm between source and target. 
                   Note: The output file passed in must be a full path."""
                if not output:
                    outputXfm = inSource.registerVolume(inTarget, defaultDir)
                    self.output = outputXfm
                else:
                    self.output = output
                    inSource.addAndSetXfmToUse(inTarget, self.output)
                    outputXfm = output
                self.logFile = fh.logFromFile(inSource.logDir, outputXfm)
                self.useMask = useMask
                if self.useMask:
                    self.source_mask = inSource.getMask()
                    self.target_mask = inTarget.getMask()
            else:
                self.source = inSource
                self.target = inTarget
                self.output = output
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), output)
                else:
                    self.logFile = logFile
                self.transform = transform
                self.useMask = useMask
                if self.useMask:
                    self.source_mask = source_mask
                    self.target_mask = target_mask 
        except:
            print "Failed in putting together minctracc command."
            print "Unexpected error: ", sys.exc_info()
        
        self.linearparam = linearparam       
        self.iterations = str(iterations)
        self.lattice_diameter = str(step*3.0)
        self.step = str(step)       
        self.weight = str(weight)
        self.stiffness = str(stiffness)
        self.similarity = str(similarity)
        self.w_translations = str(w_translations)
        self.w_rotations = str(w_rotations)
        self.w_scales = str(w_scales)
        self.w_shear = str(w_shear)
        self.simplex = str(simplex)
        self.optimization = str(optimization)

        self.addDefaults()
        self.finalizeCommand()
        self.setTransform()
        self.setName()
        self.colour = "red"
Exemple #18
0
    def __init__(self,
                 inSource,
                 inTarget,
                 output=None,
                 logFile=None,
                 defaultDir="transforms",
                 blur=None,
                 gradient=False,
                 linearparam="nlin",
                 source_mask=None,
                 target_mask=None,
                 iterations=40,
                 step=0.5,
                 transform=None,
                 weight=0.8,
                 stiffness=0.98,
                 similarity=0.8,
                 w_translations=0.4,
                 w_rotations=0.0174533,
                 w_scales=0.02,
                 w_shear=0.02,
                 simplex=1,
                 optimization="-use_simplex",
                 useMask=True):
        #MF TODO: Specify different w_translations, rotations, scales shear in each direction?
        # Now assumes same in all directions
        # Go to more general **kwargs?
        """an efficient way to add a minctracc call to a pipeline

        The constructor needs two inputFile arguments, the source and the
        target for the registration, and multiple optional arguments
        for specifying parameters. The source and the target can be
        specified as either RegistrationPipeFH instances or as strings
        representing filenames. In the latter case an output and a
        logfile filename are required as well (these are filled in
        automatically in the case of RegistrationPipeFH instances.)

        """
        CmdStage.__init__(self,
                          None)  #don't do any arg processing in superclass
        try:
            if isFileHandler(inSource, inTarget):
                """ if blur = None, getBlur returns lastblur
                if gradient is true, getBlur returns gradient instead of blur 
                if blur = -1, lastBaseVol is returned and gradient is ignored.
                
                self.transform will be None if there is no previous transform
                between input and target. If this is the case, lsq6 and lsq12
                defaults are added in the setTransforms function
                """
                self.source = inSource.getBlur(blur, gradient)
                self.target = inTarget.getBlur(blur, gradient)
                self.transform = inSource.getLastXfm(inTarget)
                """If no output transform is specified, use registerVolume to create a default.
                   If an output transform name is specified, use this as the output, and add it as the last xfm between source and target. 
                   Note: The output file passed in must be a full path."""
                if not output:
                    outputXfm = inSource.registerVolume(inTarget, defaultDir)
                    self.output = outputXfm
                else:
                    self.output = output
                    inSource.addAndSetXfmToUse(inTarget, self.output)
                    outputXfm = output
                self.logFile = fh.logFromFile(inSource.logDir, outputXfm)
                self.useMask = useMask
                if self.useMask:
                    self.source_mask = inSource.getMask()
                    self.target_mask = inTarget.getMask()
            else:
                self.source = inSource
                self.target = inTarget
                self.output = output
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), output)
                else:
                    self.logFile = logFile
                self.transform = transform
                self.useMask = useMask
                if self.useMask:
                    self.source_mask = source_mask
                    self.target_mask = target_mask
        except:
            print "Failed in putting together minctracc command."
            print "Unexpected error: ", sys.exc_info()

        self.linearparam = linearparam
        self.iterations = str(iterations)
        self.lattice_diameter = str(step * 3.0)
        self.step = str(step)
        self.weight = str(weight)
        self.stiffness = str(stiffness)
        self.similarity = str(similarity)
        self.w_translations = str(w_translations)
        self.w_rotations = str(w_rotations)
        self.w_scales = str(w_scales)
        self.w_shear = str(w_shear)
        self.simplex = str(simplex)
        self.optimization = str(optimization)

        self.addDefaults()
        self.finalizeCommand()
        self.setTransform()
        self.setName()
        self.colour = "red"
Exemple #19
0
    def __init__(
            self,
            inSource,
            inTarget,
            output=None,
            logFile=None,
            defaultDir="transforms",
            blur=[-1, 0.056],
            gradient=[False, True],
            target_mask=None,  #ANTS only uses one mask
            similarity_metric=["CC", "CC"],
            weight=[1, 1],
            iterations="100x100x100x150",
            radius_or_histo=[3, 3],
            transformation_model="SyN[0.1]",
            regularization="Gauss[2,1]",
            useMask=True):
        CmdStage.__init__(self,
                          None)  #don't do any arg processing in superclass
        try:
            if isFileHandler(inSource, inTarget):
                """Same defaults as minctracc class:
                    blur = None --> return lastblur
                    gradient = True --> return gradient instead of blur
                    if blur = -1 --> lastBaseVol returned and gradient ignored"""
                self.source = []
                self.target = []
                # Need to check that length of blur, gradient, similarity, weight
                # and radius_or_histo are the same
                self.checkArrayLengths(blur, gradient, similarity_metric,
                                       weight, radius_or_histo)
                for i in range(len(blur)):
                    self.source.append(inSource.getBlur(blur[i], gradient[i]))
                    self.target.append(inTarget.getBlur(blur[i], gradient[i]))
                """If no output transform is specified, use registerVolume to create a default.
                   If an output transform name is specified, use this as the output, and add it as the last xfm between source and target. 
                   Note: The output file passed in must be a full path."""
                if not output:
                    outputXfm = inSource.registerVolume(inTarget, defaultDir)
                    self.output = outputXfm
                else:
                    self.output = output
                    inSource.addAndSetXfmToUse(inTarget, self.output)
                self.logFile = fh.logFromFile(inSource.logDir, self.output)
                self.useMask = useMask
                if self.useMask:
                    self.target_mask = inTarget.getMask()
            else:
                self.source = inSource
                self.target = inTarget
                #MF TODO: Need to find a way to specify multiple source and targets
                #based on blur and gradient
                self.output = output
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), output)
                else:
                    self.logFile = logFile
                self.useMask = useMask
                if self.useMask:
                    self.target_mask = target_mask
        except:
            print "Failed in putting together mincANTS command."
            print "Unexpected error: ", sys.exc_info()

        self.similarity_metric = similarity_metric
        self.weight = weight
        self.iterations = iterations
        self.radius_or_histo = radius_or_histo
        """Single quotes needed on the command line for 
           transformation_model and regularization
        """
        self.transformation_model = "'" + transformation_model + "'"
        self.regularization = "'" + regularization + "'"

        self.addDefaults()
        self.finalizeCommand()
        self.setName()
        self.colour = "red"
Exemple #20
0
    def __init__(self,              
                 inFile,
                 targetFile,
                 **kwargs):
        
        """calls mincresample with the specified options

        The inFile and likeFile can be in one of two styles. 
        The first argument can be an instance of RegistrationPipeFH. 
        In this case the last volume in that instance (i.e. inFile.lastBasevol) 
        will be resampled and the output will be determined accordingly.
        Alternatively, the inFile can be a string representing a
        filename, in which case the output and logfile will be set based on 
        the inFile name.

        inFile is required, everything else optional
        This class assuming use of the most commonly used flags (-2, -clobber, -like, -transform)
        Any commands above and beyond the standard will be read in from argarray
        argarray could contain inFile and/or output files
        """
        
        argArray = kwargs.pop("argArray", None)
        if not argArray:
            CmdStage.__init__(self, ["mincresample"])
        else:
            CmdStage.__init__(self, ["mincresample"] + argArray)
          
        try:
            #MF TODO: What if we don't want to use lastBasevol?  
            if isFileHandler(inFile, targetFile):              
                self.inFile = self.getFileToResample(inFile, **kwargs)
                self.targetFile = targetFile.getLastBasevol()
                likeFile=kwargs.pop("likeFile", None)
                if likeFile:
                    if isFileHandler(likeFile):
                        self.likeFile = likeFile.getLastBasevol() 
                    else:
                        print "likeFile must be RegistrationPipeFH or RegistrationFHBase."
                        raise 
                invert = False
                for cmd in self.cmd:
                    if fnmatch.fnmatch(cmd, "*-invert*"):
                        invert = True
                        break
                xfm = kwargs.pop("transform", None)
                if xfm:
                    self.cxfm = xfm
                else:
                    if invert:
                        self.cxfm = targetFile.getLastXfm(inFile)
                    else:
                        self.cxfm = inFile.getLastXfm(targetFile)
                self.outputLocation=kwargs.pop("outputLocation", None)
                if not self.outputLocation: 
                    self.outputLocation=inFile
                else:
                    if not isFileHandler(self.outputLocation):
                        print "outputLocation must be RegistrationPipeFH or RegistrationFHBase."
                        raise
                default = kwargs.pop("defaultDir", None)
                if not default:
                    defaultDir = "resampled"
                else:
                    defaultDir = default
                """If an output file is specified, then use it, else create a default file name.
                   Note: The output file passed in must be a full path."""
                output = kwargs.pop("output", None)
                if not output:
                    self.outfile = self.setOutputFile(self.outputLocation, defaultDir)
                else:
                    self.outfile = output
                self.logFile = fh.logFromFile(self.outputLocation.logDir, self.outfile)
            else:
                self.inFile = inFile
                self.targetFile = targetFile
                self.likeFile = kwargs.pop("likeFile", None)
                self.cxfm = kwargs.pop("transform", None)
                self.outfile=kwargs.pop("output", None)
                logFile=kwargs.pop("logFile", None)
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir), self.outfile)
                else:
                    self.logFile = logFile
    
        except:
            print "Failed in putting together resample command"
            print "Unexpected error: ", sys.exc_info()
            
        self.addDefaults()
        self.finalizeCommand()
        self.setName()
        if isFileHandler(inFile, targetFile):
            self.setLastResampledFile()
Exemple #21
0
    def __init__(self, inFile, targetFile, **kwargs):
        """calls mincresample with the specified options

        The inFile and likeFile can be in one of two styles. 
        The first argument can be an instance of RegistrationPipeFH. 
        In this case the last volume in that instance (i.e. inFile.lastBasevol) 
        will be resampled and the output will be determined accordingly.
        Alternatively, the inFile can be a string representing a
        filename, in which case the output and logfile will be set based on 
        the inFile name.

        inFile is required, everything else optional
        This class assuming use of the most commonly used flags (-2, -clobber, -like, -transform)
        Any commands above and beyond the standard will be read in from argarray
        argarray could contain inFile and/or output files
        """

        argArray = kwargs.pop("argArray", None)
        if not argArray:
            CmdStage.__init__(self, ["mincresample"])
        else:
            CmdStage.__init__(self, ["mincresample"] + argArray)

        try:
            #MF TODO: What if we don't want to use lastBasevol?
            if isFileHandler(inFile, targetFile):
                self.inFile = self.getFileToResample(inFile, **kwargs)
                self.targetFile = targetFile.getLastBasevol()
                likeFile = kwargs.pop("likeFile", None)
                if likeFile:
                    if isFileHandler(likeFile):
                        self.likeFile = likeFile.getLastBasevol()
                    else:
                        print "likeFile must be RegistrationPipeFH or RegistrationFHBase."
                        raise
                invert = False
                for cmd in self.cmd:
                    if fnmatch.fnmatch(cmd, "*-invert*"):
                        invert = True
                        break
                xfm = kwargs.pop("transform", None)
                if xfm:
                    self.cxfm = xfm
                else:
                    if invert:
                        self.cxfm = targetFile.getLastXfm(inFile)
                    else:
                        self.cxfm = inFile.getLastXfm(targetFile)
                self.outputLocation = kwargs.pop("outputLocation", None)
                if not self.outputLocation:
                    self.outputLocation = inFile
                else:
                    if not isFileHandler(self.outputLocation):
                        print "outputLocation must be RegistrationPipeFH or RegistrationFHBase."
                        raise
                default = kwargs.pop("defaultDir", None)
                if not default:
                    defaultDir = "resampled"
                else:
                    defaultDir = default
                """If an output file is specified, then use it, else create a default file name.
                   Note: The output file passed in must be a full path."""
                output = kwargs.pop("output", None)
                if not output:
                    self.outfile = self.setOutputFile(self.outputLocation,
                                                      defaultDir)
                else:
                    self.outfile = output
                self.logFile = fh.logFromFile(self.outputLocation.logDir,
                                              self.outfile)
            else:
                self.inFile = inFile
                self.targetFile = targetFile
                self.likeFile = kwargs.pop("likeFile", None)
                self.cxfm = kwargs.pop("transform", None)
                self.outfile = kwargs.pop("output", None)
                logFile = kwargs.pop("logFile", None)
                if not logFile:
                    self.logFile = fh.logFromFile(abspath(curdir),
                                                  self.outfile)
                else:
                    self.logFile = logFile

        except:
            print "Failed in putting together resample command"
            print "Unexpected error: ", sys.exc_info()

        self.addDefaults()
        self.finalizeCommand()
        self.setName()
        if isFileHandler(inFile, targetFile):
            self.setLastResampledFile()
Exemple #22
0
 def __init__(self,
              inSource,
              inTarget,
              output=None,
              logFile=None,
              defaultDir="transforms", 
              blur=[-1, 0.056],
              gradient=[False, True],
              target_mask=None, #ANTS only uses one mask
              similarity_metric=["CC", "CC"],
              weight=[1,1],
              iterations="100x100x100x150",
              radius_or_histo=[3,3],
              transformation_model="SyN[0.1]", 
              regularization="Gauss[2,1]",
              useMask=True):
     CmdStage.__init__(self, None) #don't do any arg processing in superclass
     try: 
         if isFileHandler(inSource, inTarget):
             """Same defaults as minctracc class:
                 blur = None --> return lastblur
                 gradient = True --> return gradient instead of blur
                 if blur = -1 --> lastBaseVol returned and gradient ignored"""
             self.source = []
             self.target = []
             # Need to check that length of blur, gradient, similarity, weight
             # and radius_or_histo are the same
             self.checkArrayLengths(blur, 
                                    gradient, 
                                    similarity_metric,
                                    weight,
                                    radius_or_histo)
             for i in range(len(blur)):
                 self.source.append(inSource.getBlur(blur[i], gradient[i]))
                 self.target.append(inTarget.getBlur(blur[i], gradient[i]))
             """If no output transform is specified, use registerVolume to create a default.
                If an output transform name is specified, use this as the output, and add it as the last xfm between source and target. 
                Note: The output file passed in must be a full path."""
             if not output:
                 outputXfm = inSource.registerVolume(inTarget, defaultDir)
                 self.output = outputXfm
             else:
                 self.output = output
                 inSource.addAndSetXfmToUse(inTarget, self.output)
             self.logFile = fh.logFromFile(inSource.logDir, self.output)
             self.useMask=useMask
             if self.useMask:
                 self.target_mask = inTarget.getMask()
         else:
             self.source = inSource
             self.target = inTarget
             #MF TODO: Need to find a way to specify multiple source and targets
             #based on blur and gradient 
             self.output = output
             if not logFile:
                 self.logFile = fh.logFromFile(abspath(curdir), output)
             else:
                 self.logFile = logFile
             self.useMask=useMask
             if self.useMask:
                 self.target_mask = target_mask
     except:
         print "Failed in putting together mincANTS command."
         print "Unexpected error: ", sys.exc_info()
     
     self.similarity_metric = similarity_metric
     self.weight = weight 
     self.iterations = iterations
     self.radius_or_histo = radius_or_histo
     """Single quotes needed on the command line for 
        transformation_model and regularization
     """
     self.transformation_model = "'" + transformation_model + "'" 
     self.regularization = "'" + regularization + "'"
     
     self.addDefaults()
     self.finalizeCommand()
     self.setName()
     self.colour = "red"
Exemple #23
0
    def __init__(self, inFile, fwhm, defaultDir="tmp", gradient=False):
        """calls mincblur with the specified 3D Gaussian kernel

        The inputs can be in one of two styles. The first argument can
        be an instance of RegistrationPipeFH, in which case the last
        volume in that instance (i.e. inFile.lastBasevol) will be
        blurred and the output will be determined by its blurFile
        method. Alternately, the inFile can be a string representing a
        filename, in which case the output and logfile will be set based on 
        the inFile name. If the fwhm specified is -1, we do not construct 
        a command.

        """

        if fwhm == -1:
            return

        CmdStage.__init__(self, None)
        try:
            if isFileHandler(inFile):
                blurlist = inFile.blurFile(fwhm, gradient, defaultDir)
                self.base = blurlist["base"]
                self.inputFiles = [inFile.getLastBasevol()]
                self.outputFiles = [blurlist["file"]]
                self.logFile = blurlist["log"]
                self.name = "mincblur " + str(fwhm) + " " + inFile.basename
                if gradient:
                    self.outputFiles.append(blurlist["gradient"])
            else:
                self.base = str(inFile).replace(".mnc", "")
                self.inputFiles = [inFile]
                blurBase = "".join([self.base, "_fwhm", str(fwhm), "_blur"])
                output = "".join([blurBase, ".mnc"])
                self.outputFiles = [output]
                self.logFile = fh.logFromFile(abspath(curdir), output)
                self.name = "mincblur " + str(fwhm) + " " + basename(inFile)
                if gradient:
                    gradientBase = blurBase.replace("blur", "dxyz")
                    self.outputFiles += ["".join([gradientBase, ".mnc"])]
        except:
            print "Failed in putting together blur command; unexpected error: "
            raise

        self.cmd = [
            "mincblur", "-clobber", "-no_apodize", "-fwhm",
            str(fwhm), self.inputFiles[0], self.base
        ]
        if gradient:
            self.cmd += ["-gradient"]
        self.colour = "blue"

        # this is a temporary solution, but it's better to at least catch it
        # somewhere... In the mincblur code, there is a hardcoded limit for
        # the length of the output file: full_outfilename[256]; (blur_volume.c)
        # This is a limit for the basename. Added to that will be: _dxyz.mnc
        # or _blur.mnc. In total the output file names can not be longer than 264
        # characters. Given that we don't know which version of mincblur is installed
        # (this should and will be fixed at some point in the future), we'll exit here
        if len(self.outputFiles[0]) > 264:
            raise Exception(
                "mincblur (potentially) has a hardcoded limit for the allowed length of the output file. The following command will not be able to run: \n\n%s\n\nPlease rename your input files/paths to make sure the filenames become shorter.\n"
                % self.cmd)