def maskFiles(FH, isAtlas, numAtlases=1): """ Assume that if there is more than one atlas, multiple masks were generated and we need to perform a voxel_vote. Otherwise, assume we are using inputLabels from crossing with only one atlas. """ #MF TODO: Make this more general to handle pairwise option. p = Pipeline() if not isAtlas: if numAtlases > 1: voxel = voxelVote(FH, False, True) p.addStage(voxel) mincMathInput = voxel.outputFiles[0] else: mincMathInput = FH.returnLabels(True)[0] FH.setMask(mincMathInput) else: mincMathInput = FH.getMask() mincMathOutput = fh.createBaseName(FH.resampledDir, FH.basename) mincMathOutput += "_masked.mnc" logFile = fh.logFromFile(FH.logDir, mincMathOutput) cmd = ["mincmath"] + ["-clobber"] + ["-mult"] cmd += [InputFile(mincMathInput)] + [InputFile(FH.getLastBasevol())] cmd += [OutputFile(mincMathOutput)] mincMath = CmdStage(cmd) mincMath.setLogFile(LogFile(logFile)) p.addStage(mincMath) FH.setLastBasevol(mincMathOutput) return(p)
def maskFiles(FH, isAtlas, numAtlases=1): """ Assume that if there is more than one atlas, multiple masks were generated and we need to perform a voxel_vote. Otherwise, assume we are using inputLabels from crossing with only one atlas. """ #MF TODO: Make this more general to handle pairwise option. p = Pipeline() if not isAtlas: if numAtlases > 1: voxel = voxelVote(FH, False, True) p.addStage(voxel) mincMathInput = voxel.outputFiles[0] else: mincMathInput = FH.returnLabels(True)[0] FH.setMask(mincMathInput) else: mincMathInput = FH.getMask() mincMathOutput = fh.createBaseName(FH.resampledDir, FH.basename) mincMathOutput += "_masked.mnc" logFile = fh.logFromFile(FH.logDir, mincMathOutput) cmd = ["mincmath"] + ["-clobber"] + ["-mult"] cmd += [InputFile(mincMathInput)] + [InputFile(FH.getLastBasevol())] cmd += [OutputFile(mincMathOutput)] mincMath = CmdStage(cmd) mincMath.setLogFile(LogFile(logFile)) p.addStage(mincMath) FH.setLastBasevol(mincMathOutput) return (p)
def iterate(self): if not self.maxPairs: xfmsToAvg = {} lsq12ResampledFiles = {} for inputFH in self.inputs: """Create an array of xfms, to compute an average lsq12 xfm for each input""" xfmsToAvg[inputFH] = [] for targetFH in self.inputs: if inputFH != targetFH: lsq12 = LSQ12(inputFH, targetFH, self.blurs, self.stepSize, self.useGradient, self.simplex) self.p.addPipeline(lsq12.p) xfmsToAvg[inputFH].append(inputFH.getLastXfm(targetFH)) """Create average xfm for inputFH using xfmsToAvg array""" cmd = ["xfmavg"] for i in range(len(xfmsToAvg[inputFH])): cmd.append(InputFile(xfmsToAvg[inputFH][i])) avgXfmOutput = createBaseName(inputFH.transformsDir, inputFH.basename + "-avg-lsq12.xfm") cmd.append(OutputFile(avgXfmOutput)) xfmavg = CmdStage(cmd) xfmavg.setLogFile(LogFile(logFromFile(inputFH.logDir, avgXfmOutput))) self.p.addStage(xfmavg) self.lsq12AvgXfms[inputFH] = avgXfmOutput """ resample brain and add to array for mincAveraging""" if not self.likeFile: likeFile=inputFH else: likeFile=self.likeFile rslOutput = createBaseName(inputFH.resampledDir, inputFH.basename + "-resampled-lsq12.mnc") res = ma.mincresample(inputFH, inputFH, transform=avgXfmOutput, likeFile=likeFile, output=rslOutput, argArray=["-sinc"]) self.p.addStage(res) lsq12ResampledFiles[inputFH] = rslOutput """ After all registrations complete, setLastBasevol for each subject to be resampled file in lsq12 space. We can then call mincAverage on fileHandlers, as it will use the lastBasevol for each by default.""" for inputFH in self.inputs: inputFH.setLastBasevol(lsq12ResampledFiles[inputFH]) """ mincAverage all resampled brains and put in lsq12Directory""" self.lsq12Avg = abspath(self.lsq12Dir) + "/" + basename(self.lsq12Dir) + "-pairs.mnc" self.lsq12AvgFH = RegistrationPipeFH(self.lsq12Avg, basedir=self.lsq12Dir) avg = ma.mincAverage(self.inputs, self.lsq12AvgFH, output=self.lsq12Avg, defaultDir=self.lsq12Dir) self.p.addStage(avg) else: print "Registration using a specified number of max pairs not yet working. Check back soon!" sys.exit()
def linAndNlinDisplacement(self): """ The function calculates both the linear and nonlinear portions of the displacement, in order to find pure nonlinear. Common space here is the target (usually an average of some sort). We also recentre pure non linear displacement. """ """Calculate linear part of non-linear xfm from input to target""" lpnl = linearPartofNlin(self.inputFH, self.targetFH) self.p.addStage(lpnl) self.linearXfm = lpnl.outputFiles[0] """Calculate full displacement from target to input""" self.calcFullDisplacement() """Calculate pure non-linear displacement from target to input 1. Concatenate linear and inverse target to input transform to get pure_nlin xfm 2. Compute mincDisplacement on this transform. """ nlinXfm = createPureNlinXfmName(self.inputFH, self.invXfm) xc = xfmConcat([self.linearXfm, self.invXfm], nlinXfm, fh.logFromFile(self.inputFH.logDir, nlinXfm)) self.p.addStage(xc) nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=nlinXfm) self.p.addStage(nlinDisp) self.nlinDisp = nlinDisp.outputFiles[0] """Calculate average displacement and re-center non-linear displacement if an array of input file handlers was specified on instantiation. """ if self.dispToAvg: """Calculate average inverse displacement""" avgOutput = abspath(self.targetFH.basedir) + "/" + "average_inv_pure_displacement.mnc" logBase = fh.removeBaseAndExtension(avgOutput) avgLog = fh.createLogFile(self.targetFH.basedir, logBase) avg = mincAverageDisp(self.dispToAvg, avgOutput, logFile=avgLog) self.p.addStage(avg) """Centre pure nlin displacement by subtracting average from existing""" centredBase = fh.removeBaseAndExtension(self.nlinDisp).split("_displacement")[0] centredOut = fh.createBaseName(self.inputFH.statsDir, centredBase + "_centred_displacement.mnc") cmd = ["mincmath", "-clobber", "-sub", InputFile(self.nlinDisp), InputFile(avgOutput), OutputFile(centredOut)] centredDisp = CmdStage(cmd) centredDisp.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, centredOut))) self.p.addStage(centredDisp) """Reset centred displacement to be self.nlinDisp""" self.nlinDisp = centredOut
def voxelVote(inputFH, pairwise, mask): # if we do pairwise crossing, use output labels for voting (Default) # otherwise, return inputLabels from initial atlas-input crossing useInputLabels = False if not pairwise: useInputLabels = True labels = inputFH.returnLabels(useInputLabels) out = fh.createBaseName(inputFH.labelsDir, inputFH.basename) if mask: out += "_mask.mnc" else: out += "_votedlabels.mnc" logFile = fh.logFromFile(inputFH.logDir, out) cmd = ["voxel_vote"] + [InputFile(l) for l in labels] + [OutputFile(out)] voxel = CmdStage(cmd) voxel.setLogFile(LogFile(logFile)) return (voxel)
def voxelVote(inputFH, pairwise, mask): # if we do pairwise crossing, use output labels for voting (Default) # otherwise, return inputLabels from initial atlas-input crossing useInputLabels = False if not pairwise: useInputLabels = True labels = inputFH.returnLabels(useInputLabels) out = fh.createBaseName(inputFH.labelsDir, inputFH.basename) if mask: out += "_mask.mnc" else: out += "_votedlabels.mnc" logFile = fh.logFromFile(inputFH.logDir, out) cmd = ["voxel_vote.py"] + [InputFile(l) for l in labels] + [OutputFile(out)] voxel = CmdStage(cmd) voxel.setLogFile(LogFile(logFile)) return(voxel)
def voxelVote(inputFH, pairwise, mask): # In the main MAGeT.py code, when not only a mask is created for the # input files, the process works as follows: # # 1) the template files (library) are aligned to each input upto max_templates input files # 2) all templates (library + newly created) are aligned to each input # # That second stage contains alignments that have already run in the first stage. # And pydpiper is coded such, that this duplicated stage is not performed. In order # to get all labels for voxel voting, we need to combine atlases from both these # stages, i.e., the "initial" and the "templates". This means that we should always # get the "useInputLabels". (In the special case where there is only 1 input file # and pairwise is set to true, this is particularly important, because of the duplicate # stages, only the inputlabels will exists.) # 1) get the input templates # the True parameter will return "inputLabels" from the groupedFiles for inputFH labels = inputFH.returnLabels(True) # 2) if we do pairwise crossing, also get the output labels for voting if pairwise: # False will return "labels" from the groupedFiles for inputFH outputLabels = inputFH.returnLabels(False) # add these labels to the "initial" or input labels: labels = labels + outputLabels out = fh.createBaseName(inputFH.labelsDir, inputFH.basename) if mask: out += "_mask.mnc" else: out += "_votedlabels.mnc" logFile = fh.logFromFile(inputFH.logDir, out) cmd = ["voxel_vote"] + [InputFile(l) for l in labels] + [OutputFile(out)] voxel = CmdStage(cmd) voxel.setLogFile(LogFile(logFile)) return(voxel)
def maskFiles(FH, isAtlas, numAtlases=1): """ Assume that if there is more than one atlas, multiple masks were generated and we need to perform a voxel_vote. Otherwise, assume we are using inputLabels from crossing with only one atlas. """ #MF TODO: Make this more general to handle pairwise option. p = Pipeline() if not isAtlas: if numAtlases > 1: voxel = voxelVote(FH, False, True) p.addStage(voxel) mincMathInput = voxel.outputFiles[0] else: mincMathInput = FH.returnLabels(True)[0] FH.setMask(mincMathInput) else: mincMathInput = FH.getMask() mincMathOutput = fh.createBaseName(FH.resampledDir, FH.basename) mincMathOutput += "_masked.mnc" logFile = fh.logFromFile(FH.logDir, mincMathOutput) cmd = ["mincmath"] + ["-clobber"] + ["-mult"] # In response to issue #135 # the order of the input files to mincmath matters. By default the # first input files is used as a "like file" for the output file. # We should make sure that the mask is not used for that, because # it has an image range from 0 to 1; not something we want to be # set for the masked output file # average mask cmd += [InputFile(FH.getLastBasevol())] + [InputFile(mincMathInput)] cmd += [OutputFile(mincMathOutput)] mincMath = CmdStage(cmd) mincMath.setLogFile(LogFile(logFile)) p.addStage(mincMath) FH.setLastBasevol(mincMathOutput) return(p)
def maskFiles(FH, isAtlas, numAtlases=1): """ Assume that if there is more than one atlas, multiple masks were generated and we need to perform a voxel_vote. Otherwise, assume we are using inputLabels from crossing with only one atlas. """ #MF TODO: Make this more general to handle pairwise option. p = Pipeline() if not isAtlas: if numAtlases > 1: voxel = voxelVote(FH, False, True) p.addStage(voxel) mincMathInput = voxel.outputFiles[0] else: mincMathInput = FH.returnLabels(True)[0] FH.setMask(mincMathInput) else: mincMathInput = FH.getMask() mincMathOutput = fh.createBaseName(FH.resampledDir, FH.basename) mincMathOutput += "_masked.mnc" logFile = fh.logFromFile(FH.logDir, mincMathOutput) cmd = ["mincmath"] + ["-clobber"] + ["-mult"] # In response to issue #135 # the order of the input files to mincmath matters. By default the # first input files is used as a "like file" for the output file. # We should make sure that the mask is not used for that, because # it has an image range from 0 to 1; not something we want to be # set for the masked output file # average mask cmd += [InputFile(FH.getLastBasevol())] + [InputFile(mincMathInput)] cmd += [OutputFile(mincMathOutput)] mincMath = CmdStage(cmd) mincMath.setLogFile(LogFile(logFile)) p.addStage(mincMath) FH.setLastBasevol(mincMathOutput) return (p)
def voxelVote(inputFH, pairwise, mask): # In the main MAGeT.py code, when not only a mask is created for the # input files, the process works as follows: # # 1) the template files (library) are aligned to each input upto max_templates input files # 2) all templates (library + newly created) are aligned to each input # # That second stage contains alignments that have already run in the first stage. # And pydpiper is coded such, that this duplicated stage is not performed. In order # to get all labels for voxel voting, we need to combine atlases from both these # stages, i.e., the "initial" and the "templates". This means that we should always # get the "useInputLabels". (In the special case where there is only 1 input file # and pairwise is set to true, this is particularly important, because of the duplicate # stages, only the inputlabels will exists.) # 1) get the input templates # the True parameter will return "inputLabels" from the groupedFiles for inputFH labels = inputFH.returnLabels(True) # 2) if we do pairwise crossing, also get the output labels for voting if pairwise: # False will return "labels" from the groupedFiles for inputFH outputLabels = inputFH.returnLabels(False) # add these labels to the "initial" or input labels: labels = labels + outputLabels out = fh.createBaseName(inputFH.labelsDir, inputFH.basename) if mask: out += "_mask.mnc" else: out += "_votedlabels.mnc" logFile = fh.logFromFile(inputFH.logDir, out) cmd = ["voxel_vote"] + [InputFile(l) for l in labels] + [OutputFile(out)] voxel = CmdStage(cmd) voxel.setLogFile(LogFile(logFile)) return (voxel)
def iterate(self): if not self.maxPairs: xfmsToAvg = {} lsq12ResampledFiles = {} for inputFH in self.inputs: """Create an array of xfms, to compute an average lsq12 xfm for each input""" xfmsToAvg[inputFH] = [] for targetFH in self.inputs: if inputFH != targetFH: lsq12 = LSQ12(inputFH, targetFH, blurs=self.blurs, step=self.stepSize, gradient=self.useGradient, simplex=self.simplex, w_translations=self.w_translations) self.p.addPipeline(lsq12.p) xfmsToAvg[inputFH].append(inputFH.getLastXfm(targetFH)) """Create average xfm for inputFH using xfmsToAvg array""" cmd = ["xfmavg"] for i in range(len(xfmsToAvg[inputFH])): cmd.append(InputFile(xfmsToAvg[inputFH][i])) avgXfmOutput = createBaseName( inputFH.transformsDir, inputFH.basename + "-avg-lsq12.xfm") cmd.append(OutputFile(avgXfmOutput)) xfmavg = CmdStage(cmd) xfmavg.setLogFile( LogFile(logFromFile(inputFH.logDir, avgXfmOutput))) self.p.addStage(xfmavg) self.lsq12AvgXfms[inputFH] = avgXfmOutput """ resample brain and add to array for mincAveraging""" if not self.likeFile: likeFile = inputFH else: likeFile = self.likeFile rslOutput = createBaseName( inputFH.resampledDir, inputFH.basename + "-resampled-lsq12.mnc") res = ma.mincresample(inputFH, inputFH, transform=avgXfmOutput, likeFile=likeFile, output=rslOutput, argArray=["-sinc"]) self.p.addStage(res) lsq12ResampledFiles[inputFH] = rslOutput """ After all registrations complete, setLastBasevol for each subject to be resampled file in lsq12 space. We can then call mincAverage on fileHandlers, as it will use the lastBasevol for each by default.""" for inputFH in self.inputs: inputFH.setLastBasevol(lsq12ResampledFiles[inputFH]) """ mincAverage all resampled brains and put in lsq12Directory""" self.lsq12Avg = abspath(self.lsq12Dir) + "/" + basename( self.lsq12Dir) + "-pairs.mnc" self.lsq12AvgFH = RegistrationPipeFH(self.lsq12Avg, basedir=self.lsq12Dir) avg = ma.mincAverage(self.inputs, self.lsq12AvgFH, output=self.lsq12Avg, defaultDir=self.lsq12Dir) self.p.addStage(avg) else: print "Registration using a specified number of max pairs not yet working. Check back soon!" sys.exit()
def calcDetAndLogDet(self, useFullDisp=False): if useFullDisp: dispToUse = self.fullDisp #absolute jacobians else: dispToUse = self.nlinDisp #relative jacobians """Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians.""" self.blurs.insert(0,-1) for b in self.blurs: """Create base name for determinant calculation.""" outputBase = fh.removeBaseAndExtension(dispToUse).split("_displacement")[0] """Calculate smoothed deformation field for all blurs other than -1""" if b != -1: fwhm = "--fwhm=" + str(b) outSmooth = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_smooth_displacement_fwhm" + str(b) + ".mnc") cmd = ["smooth_vector", "--clobber", "--filter", fwhm, InputFile(dispToUse), OutputFile(outSmooth)] smoothVec = CmdStage(cmd) smoothVec.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outSmooth))) self.p.addStage(smoothVec) """Set input for determinant calculation.""" inputDet = outSmooth nameAddendum = "_fwhm" + str(b) else: inputDet = dispToUse nameAddendum = "" outputDet = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_determinant" + nameAddendum + ".mnc") outDetShift = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_det_plus1" + nameAddendum + ".mnc") if useFullDisp: #absolute jacobians outLogDet = fh.createBaseName(self.inputFH.statsDir, outputBase + "_absolute_log_determinant" + nameAddendum + ".mnc") else: #relative jacobians outLogDet = fh.createBaseName(self.inputFH.statsDir, outputBase + "_relative_log_determinant" + nameAddendum + ".mnc") """Calculate the determinant, then add 1 (per mincblob weirdness)""" cmd = ["mincblob", "-clobber", "-determinant", InputFile(inputDet), OutputFile(outputDet)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outputDet))) self.p.addStage(det) cmd = ["mincmath", "-clobber", "-2", "-const", str(1), "-add", InputFile(outputDet), OutputFile(outDetShift)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outDetShift))) self.p.addStage(det) """Calculate log determinant (jacobian) and add to statsGroup.""" cmd = ["mincmath", "-clobber", "-2", "-log", InputFile(outDetShift), OutputFile(outLogDet)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDet))) self.p.addStage(det) if useFullDisp: self.statsGroup.absoluteJacobians[b] = outLogDet else: self.statsGroup.relativeJacobians[b] = outLogDet
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 iterate(self): xfmsToAvg = {} lsq12ResampledFiles = {} for inputFH in self.inputs: """Create an array of xfms, to compute an average lsq12 xfm for each input""" xfmsToAvg[inputFH] = [] if self.maxPairs is not None: if self.maxPairs >= len(self.inputs) - 1: # -1 prevents unnecessary sampling in the case self.maxPairs = len(self.inputs) - 1 inputs = self.inputs else: random.seed( tuple(map(lambda fh: fh.inputFileName, self.inputs))) # if inputFH is included in the sample, we will register against one fewer target inputs = random.sample( filter(lambda fh: fh != inputFH, self.inputs), self.maxPairs) else: inputs = self.inputs for targetFH in inputs: if inputFH != targetFH: lsq12 = LSQ12(inputFH, targetFH, blurs=self.blurs, step=self.stepSize, gradient=self.useGradient, simplex=self.simplex, w_translations=self.w_translations) self.p.addPipeline(lsq12.p) xfmsToAvg[inputFH].append(inputFH.getLastXfm(targetFH)) """Create average xfm for inputFH using xfmsToAvg array""" avgXfmOutput = createBaseName(inputFH.transformsDir, inputFH.basename + "-avg-lsq12.xfm") cmd = ["xfmavg", "-verbose", "-clobber"] \ + map(InputFile, xfmsToAvg[inputFH]) + [OutputFile(avgXfmOutput)] #for i in range(len(xfmsToAvg[inputFH])): # cmd.append(InputFile(xfmsToAvg[inputFH][i])) # '-clobber' works around #157, but is probably better in general #cmd.append(OutputFile(avgXfmOutput)) xfmavg = CmdStage(cmd) xfmavg.setLogFile( LogFile(logFromFile(inputFH.logDir, avgXfmOutput))) self.p.addStage(xfmavg) self.lsq12AvgXfms[inputFH] = avgXfmOutput """ resample brain and add to array for mincAveraging""" if not self.likeFile: likeFile = inputFH else: likeFile = self.likeFile rslOutput = createBaseName( inputFH.resampledDir, inputFH.basename + "-resampled-lsq12.mnc") res = ma.mincresample(inputFH, inputFH, transform=avgXfmOutput, likeFile=likeFile, output=rslOutput, argArray=["-sinc"]) self.p.addStage(res) lsq12ResampledFiles[inputFH] = rslOutput """ After all registrations complete, setLastBasevol for each subject to be resampled file in lsq12 space. We can then call mincAverage on fileHandlers, as it will use the lastBasevol for each by default.""" for inputFH in self.inputs: inputFH.setLastBasevol(lsq12ResampledFiles[inputFH]) """ mincAverage all resampled brains and put in lsq12Directory""" self.lsq12Avg = abspath(self.lsq12Dir) + "/" + basename( self.lsq12Dir) + "-pairs.mnc" self.lsq12AvgFH = RegistrationPipeFH(self.lsq12Avg, basedir=self.lsq12Dir) avg = ma.mincAverage(inputs, self.lsq12AvgFH, output=self.lsq12Avg, defaultDir=self.lsq12Dir) self.p.addStage(avg)
def calcDetAndLogDet(self, useFullDisp=False): #Lots of repetition here--let's see if we can't make some functions. """useFullDisp indicates whether or not to use full displacement field or non-linear component only""" if useFullDisp: dispToUse = self.fullDisp else: dispToUse = self.nlinDisp """Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians.""" self.blurs.insert(0,-1) for b in self.blurs: """Calculate default output filenames and set input for determinant calculation.""" outputBase = fh.removeBaseAndExtension(dispToUse).split("_displacement")[0] inputDet = dispToUse outputDet = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_determinant.mnc") outDetShift = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_det_plus1.mnc") outLogDet = fh.createBaseName(self.inputFH.statsDir, outputBase + "_log_determinant.mnc") outLogDetScaled = fh.createBaseName(self.inputFH.statsDir, outputBase + "_log_determinant_scaled.mnc") """Calculate smoothed deformation field for all blurs other than -1""" if b != -1: fwhm = "--fwhm=" + str(b) outSmooth = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_smooth_displacement_fwhm" + str(b) + ".mnc") cmd = ["smooth_vector", "--clobber", "--filter", fwhm, InputFile(dispToUse), OutputFile(outSmooth)] smoothVec = CmdStage(cmd) smoothVec.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outSmooth))) self.p.addStage(smoothVec) """Override file name defaults for each blur and set input for determinant calculation.""" inputDet = outSmooth outputDet = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_determinant_fwhm" + str(b) + ".mnc") outDetShift = fh.createBaseName(self.inputFH.tmpDir, outputBase + "_det_plus1_fwhm" + str(b) + ".mnc") outLogDet = fh.createBaseName(self.inputFH.statsDir, outputBase + "_log_determinant_fwhm" + str(b) + ".mnc") outLogDetScaled = fh.createBaseName(self.inputFH.statsDir, outputBase + "_log_determinant_scaled_fwhm" + str(b) + ".mnc") """Calculate the determinant, then add 1 (per mincblob weirdness)""" cmd = ["mincblob", "-clobber", "-determinant", InputFile(inputDet), OutputFile(outputDet)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outputDet))) self.p.addStage(det) cmd = ["mincmath", "-clobber", "-2", "-const", str(1), "-add", InputFile(outputDet), OutputFile(outDetShift)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outDetShift))) self.p.addStage(det) """Calculate log determinant (jacobian) and add to statsGroup.""" cmd = ["mincmath", "-clobber", "-2", "-log", InputFile(outDetShift), OutputFile(outLogDet)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDet))) self.p.addStage(det) self.statsGroup.jacobians[b] = outLogDet """If self.linearXfm present, calculate scaled log determinant (scaled jacobian) and add to statsGroup""" if not useFullDisp: """ If self.scaleFactor is specified, then concatenate this additional transform with self.linearXfm. Typically, this will come from an LSQ12 registration, but may come from another alignment. """ if self.scalingFactor: toConcat = [self.scalingFactor, self.linearXfm] self.fullLinearXfm = fh.createBaseName(self.inputFH.transformsDir, self.inputFH.basename + "_full_linear.xfm") logFile=fh.logFromFile(self.inputFH.logDir, fh.removeBaseAndExtension(self.fullLinearXfm)) concat = xfmConcat(toConcat, self.fullLinearXfm, logFile=logFile) self.p.addStage(concat) else: self.fullLinearXfm = self.linearXfm cmd = ["scale_voxels", "-clobber", "-invert", "-log", InputFile(self.fullLinearXfm), InputFile(outLogDet), OutputFile(outLogDetScaled)] det = CmdStage(cmd) det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDetScaled))) self.p.addStage(det) self.statsGroup.scaledJacobians[b] = outLogDetScaled else: self.statsGroup.scaledJacobians = None