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"
def __init__(self, inFile, targetFile, **kwargs): self.initInputLabels(kwargs.pop("setInputLabels", None)) mincresample.__init__(self, inFile, targetFile, **kwargs) if isFileHandler(self.outputLocation): #After other initialization, addLabels to appropriate array self.addLabelsToArray(self.outputLocation)
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"
def __init__(self, inFile, targetFile, nameForStage=None, **kwargs): self.p = Pipeline() self.outputFiles = [] # this will contain the outputFiles from the mincresample of the main MINC file self.outputFilesMask = [] # this will contain the outputFiles from the mincresample of the mask belonging to the main MINC file # the first step is to simply run the mincresample command: fileRS = mincresample(inFile, targetFile, **kwargs) if(nameForStage): fileRS.name = nameForStage self.p.addStage(fileRS) self.outputFiles = fileRS.outputFiles # initialize the array of outputs for the mask in case there is none to be resampled self.outputFilesMask = [None] * len(self.outputFiles) # next up, is this a file handler, and if so is there a mask that needs to be resampled? if(isFileHandler(inFile)): if(inFile.getMask()): # there is a mask associated with this file, should be updated # we have to watch out in terms of interpolation arguments, if # the original resample command asked for "-sinc" or "-tricubic" # for instance, we should remove that argument for the mask resampling # these options would reside in the argArray... maskArgs = copy.deepcopy(kwargs) if(maskArgs["argArray"]): argList = maskArgs["argArray"] for i in range(len(argList)): if(re.match("-sinc", argList[i]) or re.match("-trilinear", argList[i]) or re.match("-tricubic", argList[i]) ): del argList[i] maskArgs["argArray"] = argList # if the output file for the mincresample command was already # specified, add "_mask.mnc" to it if(maskArgs["output"]): maskArgs["output"] = re.sub(".mnc", "_mask.mnc", maskArgs["output"]) maskRS = mincresampleMask(inFile, targetFile, **maskArgs) if(nameForStage): maskRS.name = nameForStage + "--mask--" self.p.addStage(maskRS) self.outputFilesMask = maskRS.outputFiles
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"
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"
def __init__(self, inFile, targetFile, nameForStage=None, **kwargs): self.p = Pipeline() self.outputFiles = [ ] # this will contain the outputFiles from the mincresample of the main MINC file self.outputFilesMask = [ ] # this will contain the outputFiles from the mincresample of the mask belonging to the main MINC file # the first step is to simply run the mincresample command: fileRS = mincresample(inFile, targetFile, **kwargs) if (nameForStage): fileRS.name = nameForStage self.p.addStage(fileRS) self.outputFiles = fileRS.outputFiles # initialize the array of outputs for the mask in case there is none to be resampled self.outputFilesMask = [None] * len(self.outputFiles) # next up, is this a file handler, and if so is there a mask that needs to be resampled? if (isFileHandler(inFile)): if (inFile.getMask()): # there is a mask associated with this file, should be updated # we have to watch out in terms of interpolation arguments, if # the original resample command asked for "-sinc" or "-tricubic" # for instance, we should remove that argument for the mask resampling # these options would reside in the argArray... maskArgs = copy.deepcopy(kwargs) if maskArgs.has_key("argArray"): argList = maskArgs["argArray"] for i in range(len(argList)): if (re.match("-sinc", argList[i]) or re.match("-trilinear", argList[i]) or re.match("-tricubic", argList[i])): del argList[i] maskArgs["argArray"] = argList # if the output file for the mincresample command was already # specified, add "_mask.mnc" to it if maskArgs.has_key("output"): maskArgs["output"] = re.sub(".mnc", "_mask.mnc", maskArgs["output"]) maskRS = mincresampleMask(inFile, targetFile, **maskArgs) if (nameForStage): maskRS.name = nameForStage + "--mask--" self.p.addStage(maskRS) self.outputFilesMask = maskRS.outputFiles
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()
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()
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()
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()
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()
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()
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()
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()
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()
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()
def __init__(self, inputFiles, createMontage=True, montageOutPut=None, scalingFactor=20, message="lsq6"): self.p = Pipeline() self.individualImages = [] self.individualImagesLabeled = [] self.message = message if createMontage and montageOutPut == None: print("\nError: createMontage is specified in createQualityControlImages, but no output name for the montage is provided. Exiting...\n") sys.exit() # for each of the input files, run a mincpik call and create # a triplane image. for inFile in inputFiles: if isFileHandler(inFile): # create command using last base vol inputToMincpik = inFile.getLastBasevol() outputMincpik = createBaseName(inFile.tmpDir, removeBaseAndExtension(inputToMincpik) + "_QC_image.png") cmd = ["mincpik", "-clobber", "-scale", scalingFactor, "-triplanar", InputFile(inputToMincpik), OutputFile(outputMincpik)] mincpik = CmdStage(cmd) mincpik.setLogFile(LogFile(logFromFile(inFile.logDir, outputMincpik))) self.p.addStage(mincpik) self.individualImages.append(outputMincpik) # we should add a label to each of the individual images # so it will be easier for the user to identify what # which images potentially fail outputConvert = createBaseName(inFile.tmpDir, removeBaseAndExtension(inputToMincpik) + "_QC_image_labeled.png") cmdConvert = ["convert", "-label", inFile.basename, InputFile(outputMincpik), OutputFile(outputConvert)] convertAddLabel = CmdStage(cmdConvert) convertAddLabel.setLogFile(LogFile(logFromFile(inFile.logDir, outputConvert))) self.p.addStage(convertAddLabel) self.individualImagesLabeled.append(outputConvert) # if montageOutput is specified, create the overview image if createMontage: cmdmontage = ["montage", "-geometry", "+2+2"] \ + map(InputFile, self.individualImagesLabeled) + [OutputFile(montageOutPut)] montage = CmdStage(cmdmontage) montage.setLogFile(splitext(montageOutPut)[0] + ".log") message_to_print = "\n* * * * * * *\nPlease consider the following verification " message_to_print += "image, which shows a slice through all input " message_to_print += "files %s. " % self.message message_to_print += "\n%s\n" % (montageOutPut) message_to_print += "* * * * * * *\n" # the hook needs a return. Given that "print" does not return # anything, we need to encapsulate the print statement in a # function (which in this case will return None, but that's fine) def printMessageForMontage(): print(message_to_print) montage.finished_hooks.append( lambda : printMessageForMontage()) self.p.addStage(montage)
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"
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()
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()
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"
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"
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"
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)
def __init__(self, inFile, targetFile, **kwargs): self.initInputLabels(kwargs.pop("setInputLabels", None)) mincresample.__init__(self, inFile, targetFile, **kwargs) if isFileHandler(self.outputLocation): #After other initialization, addLabels to appropriate array self.addLabelsToArray(self.outputLocation)