Ejemplo n.º 1
0
 def statsAndConcat(self, s, i, count, beforeAvg=True):
     """Construct array to common space for this timepoint.
        This builds upon arrays from previous calls."""
     if beforeAvg:
         xfm = s[i].getLastXfm(s[i + 1])
     else:
         xfm = s[i].getLastXfm(s[i - 1])
     """Set this transform as last xfm from input to nlin and calculate nlin to s[i] stats"""
     if self.nlinFH:
         self.xfmToCommon.insert(0, xfm)
         """ Concat transforms to get xfmToCommon and calculate statistics 
             Note that inverted transform, which is what we want, is calculated in
             the statistics module. """
         xtc = fh.createBaseName(
             s[i].transformsDir,
             s[i].basename + "_to_" + self.commonName + ".xfm")
         xc = ma.xfmConcat(self.xfmToCommon, xtc,
                           fh.logFromFile(s[i].logDir, xtc))
         self.p.addStage(xc)
         s[i].addAndSetXfmToUse(self.nlinFH, xtc)
         self.statsCalculation(s[i],
                               self.nlinFH,
                               xfm=None,
                               useChainStats=False)
     else:
         xtc = None
     """Calculate i to i+1 stats for all but final timePoint"""
     if count - i > 1:
         self.statsCalculation(s[i], s[i + 1], xfm=xtc, useChainStats=True)
Ejemplo n.º 2
0
 def linAndNlinDisplacement(self):    
     """The function calculates both the linear and nonlinear
        portions of the displacement, in order to find 
        pure nonlinear. Input is the commonSpace, so the pure
        nonlinear displacement will point from input to target.
     
        This is opposite from the standard stats class, where
        the common space is the target
        
     """
     
     """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]
     
     """Invert the transform, so we get the linear xfm from target to input."""
     xi = xfmInvert(self.linearXfm, FH=self.inputFH)
     self.p.addStage(xi)
     
     """Calculate full displacement from input to target"""
     self.calcFullDisplacement()
     
     """Calculate pure non-linear displacement from input to target
        1. Concatenate inverse linear and full input-target xfm to 
           get pure_nlin xfm
        2. Compute mincDisplacement on this transform. 
     """
     nlinBase = fh.removeBaseAndExtension(self.xfm) + "_pure_nlin.xfm"
     nlinXfm = fh.createBaseName(self.inputFH.tmpDir, nlinBase)
     xc = xfmConcat([xi.outputFiles[0], self.xfm], nlinXfm, fh.logFromFile(self.inputFH.logDir, nlinXfm))
     self.p.addStage(xc)
     nlinDisp = mincDisplacement(self.inputFH, self.inputFH, nlinXfm)
     self.p.addStage(nlinDisp)
     self.nlinDisp = nlinDisp.outputFiles[0]
Ejemplo n.º 3
0
 def statsAndConcat(self, s, i, count, beforeAvg=True):
     """Construct array to common space for this timepoint.
        This builds upon arrays from previous calls."""
     if beforeAvg:
         xfm = s[i].getLastXfm(s[i+1]) 
     else:
         xfm = s[i].getLastXfm(s[i-1])
     """Set this transform as last xfm from input to nlin and calculate nlin to s[i] stats"""
     if self.nlinFH:
         self.xfmToCommon.insert(0, xfm)
         """ Concat transforms to get xfmToCommon and calculate statistics 
             Note that inverted transform, which is what we want, is calculated in
             the statistics module. """
         xtc = createBaseName(s[i].transformsDir, s[i].basename + "_to_" + self.commonName + ".xfm")
         xc = ma.xfmConcat(self.xfmToCommon, xtc, fh.logFromFile(s[i].logDir, xtc))
         self.p.addStage(xc)
         # here in order to visually inspect the alignment with the common
         # time point, we should resample this subject:
         inputResampledToCommon = createBaseName(s[i].resampledDir, s[i].basename + "_to_" + self.commonName + ".mnc") 
         logToCommon = fh.logFromFile(s[i].logDir, inputResampledToCommon)
         resampleCmd = ma.mincresample(s[i],
                                       self.nlinFH,
                                       likeFile=self.nlinFH,
                                       transform=xtc,
                                       output=inputResampledToCommon,
                                       logFile=logToCommon,
                                       argArray=["-sinc"])
         self.p.addStage(resampleCmd)
         s[i].addAndSetXfmToUse(self.nlinFH, xtc)
         self.statsCalculation(s[i], self.nlinFH, xfm=None, useChainStats=False)
     else:
         xtc=None
     """Calculate i to i+1 stats for all but final timePoint"""
     if count - i > 1:
         self.statsCalculation(s[i], s[i+1], xfm=xtc, useChainStats=True)
Ejemplo n.º 4
0
    def buildPipeline(self):
        # Run lsq12 registration prior to non-linear
        self.lsq12Params = mp.setLSQ12MinctraccParams(
            self.fileRes,
            subject_matter=self.subject_matter,
            reg_protocol=self.lsq12_protocol)
        lsq12reg = lsq12.LSQ12(self.inputFH,
                               self.targetFH,
                               blurs=self.lsq12Params.blurs,
                               step=self.lsq12Params.stepSize,
                               gradient=self.lsq12Params.useGradient,
                               simplex=self.lsq12Params.simplex,
                               w_translations=self.lsq12Params.w_translations,
                               defaultDir=self.defaultDir)
        self.p.addPipeline(lsq12reg.p)

        #Resample using final LSQ12 transform and reset last base volume.
        res = ma.mincresample(self.inputFH,
                              self.targetFH,
                              likeFile=self.targetFH,
                              argArray=["-sinc"])
        self.p.addStage(res)
        self.inputFH.setLastBasevol(res.outputFiles[0])
        lsq12xfm = self.inputFH.getLastXfm(self.targetFH)

        #Get registration parameters from nlin protocol, blur and register
        #Assume a SINGLE generation here.
        self.nlinParams = mp.setOneGenMincANTSParams(
            self.fileRes, reg_protocol=self.nlin_protocol)
        for b in self.nlinParams.blurs:
            for j in b:
                #Note that blurs for ANTS params in an array of arrays.
                if j != -1:
                    self.p.addStage(ma.blur(self.targetFH, j, gradient=True))
                    self.p.addStage(ma.blur(self.inputFH, j, gradient=True))

        sp = ma.mincANTS(
            self.inputFH,
            self.targetFH,
            defaultDir=self.defaultDir,
            blur=self.nlinParams.blurs[0],
            gradient=self.nlinParams.gradient[0],
            similarity_metric=self.nlinParams.similarityMetric[0],
            weight=self.nlinParams.weight[0],
            iterations=self.nlinParams.iterations[0],
            radius_or_histo=self.nlinParams.radiusHisto[0],
            transformation_model=self.nlinParams.transformationModel[0],
            regularization=self.nlinParams.regularization[0],
            useMask=self.nlinParams.useMask[0])
        self.p.addStage(sp)
        nlinXfm = sp.outputFiles[0]
        #Reset last base volume to original input for future registrations.
        self.inputFH.setLastBasevol(setToOriginalInput=True)
        #Concatenate transforms to get final lsq12 + nlin. Register volume handles naming and setting of lastXfm
        output = self.inputFH.registerVolume(self.targetFH, "transforms")
        xc = ma.xfmConcat([lsq12xfm, nlinXfm], output,
                          fh.logFromFile(self.inputFH.logDir, output))
        self.p.addStage(xc)
Ejemplo n.º 5
0
    def buildPipeline(self):
        lsq12LikeFH = None
        resolutionForLSQ12 = None
        if self.initModel:
            lsq12LikeFH = self.initModel[0]
        elif self.options.lsq12_likeFile:
            lsq12LikeFH = self.options.lsq12_likeFile

        if lsq12LikeFH == None and self.options.lsq12_subject_matter == None:
            print "\nError: the FullIterativeLSQ12Nlin module was called without specifying either an initial model, nor an lsq12_subject_matter. Currently that means that the code can not determine the resolution at which the registrations should be run. Please specify one of the two. Exiting\n"
            sys.exit()

        if not (lsq12LikeFH == None):
            resolutionForLSQ12 = rf.returnFinestResolution(lsq12LikeFH)

        lsq12module = lsq12.FullLSQ12(
            self.inputs,
            self.dirs.lsq12Dir,
            likeFile=lsq12LikeFH,
            maxPairs=self.options.lsq12_max_pairs,
            lsq12_protocol=self.options.lsq12_protocol,
            subject_matter=self.options.lsq12_subject_matter,
            resolution=resolutionForLSQ12)
        lsq12module.iterate()
        self.p.addPipeline(lsq12module.p)
        self.lsq12Params = lsq12module.lsq12Params
        if lsq12module.lsq12AvgFH.getMask() == None:
            if self.initModel:
                lsq12module.lsq12AvgFH.setMask(self.initModel[0].getMask())
        if not self.avgPrefix:
            self.avgPrefix = self.options.pipeline_name
        # same as in MBM.py:
        # for now we can use the same resolution for the NLIN stages as we did for the
        # LSQ12 stage. At some point we should look into the subject matter option...
        nlinModule = nlin.initializeAndRunNLIN(
            self.dirs.lsq12Dir,
            self.inputs,
            self.dirs.nlinDir,
            avgPrefix=self.avgPrefix,
            createAvg=False,
            targetAvg=lsq12module.lsq12AvgFH,
            nlin_protocol=self.options.nlin_protocol,
            reg_method=self.options.reg_method,
            resolution=resolutionForLSQ12)
        self.p.addPipeline(nlinModule.p)
        self.nlinFH = nlinModule.nlinAverages[-1]
        self.nlinParams = nlinModule.nlinParams
        self.initialTarget = nlinModule.initialTarget
        # Now we need the full transform to go back to LSQ6 space
        for i in self.inputs:
            linXfm = lsq12module.lsq12AvgXfms[i]
            nlinXfm = i.getLastXfm(self.nlinFH)
            outXfm = st.createOutputFileName(i, nlinXfm, "transforms",
                                             "_with_additional.xfm")
            xc = ma.xfmConcat([linXfm, nlinXfm], outXfm,
                              fh.logFromFile(i.logDir, outXfm))
            self.p.addStage(xc)
            i.addAndSetXfmToUse(self.nlinFH, outXfm)
Ejemplo n.º 6
0
 def calcNlinDisplacement(self):
     """Calculate pure non-linear displacement from target to input
        1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm   
        2. Compute mincDisplacement on this transform. 
     """
     pureNlinXfm = createOutputFileName(self.inputFH, self.invXfm, "transforms", "_pure_nlin.xfm")
     xc = xfmConcat([self.invXfm, self.linearPartOfNlinXfm], 
                    pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
     self.p.addStage(xc)
     nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=pureNlinXfm)
     self.p.addStage(nlinDisp)
     self.nlinDisp = nlinDisp.outputFiles[0]
Ejemplo n.º 7
0
 def calcNlinDisplacement(self):
     """Calculate pure non-linear displacement from target to input
        1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm   
        2. Compute mincDisplacement on this transform. 
     """
     pureNlinXfm = createOutputFileName(self.inputFH, self.invXfm, "transforms", "_pure_nlin.xfm")
     xc = xfmConcat([self.invXfm, self.linearPartOfNlinXfm], 
                    pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
     self.p.addStage(xc)
     nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=pureNlinXfm)
     self.p.addStage(nlinDisp)
     self.nlinDisp = nlinDisp.outputFiles[0]
Ejemplo n.º 8
0
 def buildPipeline(self):
     # Run lsq12 registration prior to non-linear
     self.lsq12Params = mp.setLSQ12MinctraccParams(self.fileRes, 
                                                   subject_matter=self.subject_matter,
                                                   reg_protocol=self.lsq12_protocol)
     lsq12reg = lsq12.LSQ12(self.inputFH, 
                            self.targetFH, 
                            blurs=self.lsq12Params.blurs,
                            step=self.lsq12Params.stepSize,
                            gradient=self.lsq12Params.useGradient,
                            simplex=self.lsq12Params.simplex,
                            w_translations=self.lsq12Params.w_translations,
                            defaultDir=self.defaultDir)
     self.p.addPipeline(lsq12reg.p)
     
     #Resample using final LSQ12 transform and reset last base volume. 
     res = ma.mincresample(self.inputFH, self.targetFH, likeFile=self.targetFH, argArray=["-sinc"])   
     self.p.addStage(res)
     self.inputFH.setLastBasevol(res.outputFiles[0])
     lsq12xfm = self.inputFH.getLastXfm(self.targetFH)
     
     #Get registration parameters from nlin protocol, blur and register
     #Assume a SINGLE generation here. 
     self.nlinParams = mp.setOneGenMincANTSParams(self.fileRes, reg_protocol=self.nlin_protocol)
     for b in self.nlinParams.blurs:
         for j in b:
             #Note that blurs for ANTS params in an array of arrays. 
             if j != -1:            
                 self.p.addStage(ma.blur(self.targetFH, j, gradient=True))
                 self.p.addStage(ma.blur(self.inputFH, j, gradient=True))
                 
     sp = ma.mincANTS(self.inputFH,
                      self.targetFH,
                      defaultDir=self.defaultDir, 
                      blur=self.nlinParams.blurs[0],
                      gradient=self.nlinParams.gradient[0],
                      similarity_metric=self.nlinParams.similarityMetric[0],
                      weight=self.nlinParams.weight[0],
                      iterations=self.nlinParams.iterations[0],
                      radius_or_histo=self.nlinParams.radiusHisto[0],
                      transformation_model=self.nlinParams.transformationModel[0], 
                      regularization=self.nlinParams.regularization[0],
                      useMask=self.nlinParams.useMask[0])
     self.p.addStage(sp)
     nlinXfm = sp.outputFiles[0]
     #Reset last base volume to original input for future registrations.
     self.inputFH.setLastBasevol(setToOriginalInput=True)
     #Concatenate transforms to get final lsq12 + nlin. Register volume handles naming and setting of lastXfm
     output = self.inputFH.registerVolume(self.targetFH, "transforms")
     xc = ma.xfmConcat([lsq12xfm, nlinXfm], output, fh.logFromFile(self.inputFH.logDir, output))
     self.p.addStage(xc)
Ejemplo n.º 9
0
 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
Ejemplo n.º 10
0
 def calcFullDisplacement(self):
     """Calculate full displacement from target to input. If an
        additionaXfm is specified, it is concatenated to self.xfm here """
     if self.additionalXfm:
         outXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_with_additional.xfm")
         xc = xfmConcat([self.additionalXfm, self.xfm], outXfm, fh.logFromFile(self.inputFH.logDir, outXfm))
         self.p.addStage(xc)
         xi = xfmInvert(xc.outputFiles[0], FH=self.inputFH)
         self.p.addStage(xi)
         fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=xi.outputFiles[0])
     else:
         fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=self.invXfm)
     self.p.addStage(fullDisp)
     self.fullDisp = fullDisp.outputFiles[0]
Ejemplo n.º 11
0
 def calcFullDisplacement(self):
     """Calculate full displacement from target to input. If an
        additionaXfm is specified, it is concatenated to self.xfm here """
     if self.additionalXfm:
         outXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_with_additional.xfm")
         xc = xfmConcat([self.additionalXfm, self.xfm], outXfm, fh.logFromFile(self.inputFH.logDir, outXfm))
         self.p.addStage(xc)
         xi = xfmInvert(xc.outputFiles[0], FH=self.inputFH)
         self.p.addStage(xi)
         fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=xi.outputFiles[0])
     else:
         fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=self.invXfm)
     self.p.addStage(fullDisp)
     self.fullDisp = fullDisp.outputFiles[0]
Ejemplo n.º 12
0
 def calcNlinDisplacement(self):
     """Calculate pure non-linear displacement from input to target 
        1. Invert the linear transform, so we get the linear xfm from target to input.
        2. Concatenate the full non-linear (input to target) transform with the
           linear target to input transform.
        3. Calculate the displacement on this transform. """
     xi = xfmInvert(self.linearPartOfNlinXfm, FH=self.inputFH)
     self.p.addStage(xi)
     
     pureNlinXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_pure_nlin.xfm")
     xc = xfmConcat([self.xfm, xi.outputFiles[0]], 
                    pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
     self.p.addStage(xc)
     nlinDisp = mincDisplacement(self.inputFH, self.inputFH, transform=pureNlinXfm)
     self.p.addStage(nlinDisp)
     self.nlinDisp = nlinDisp.outputFiles[0]
Ejemplo n.º 13
0
 def calcNlinDisplacement(self):
     """Calculate pure non-linear displacement from input to target 
        1. Invert the linear transform, so we get the linear xfm from target to input.
        2. Concatenate the full non-linear (input to target) transform with the
           linear target to input transform.
        3. Calculate the displacement on this transform. """
     xi = xfmInvert(self.linearPartOfNlinXfm, FH=self.inputFH)
     self.p.addStage(xi)
     
     pureNlinXfm = createOutputFileName(self.inputFH, self.xfm, "transforms", "_pure_nlin.xfm")
     xc = xfmConcat([self.xfm, xi.outputFiles[0]], 
                    pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))
     self.p.addStage(xc)
     nlinDisp = mincDisplacement(self.inputFH, self.inputFH, transform=pureNlinXfm)
     self.p.addStage(nlinDisp)
     self.nlinDisp = nlinDisp.outputFiles[0]
Ejemplo n.º 14
0
 def buildPipeline(self):
     lsq12LikeFH = None 
     if self.initModel:
         lsq12LikeFH = self.initModel[0]
     elif self.options.lsq12_likeFile: 
         lsq12LikeFH = self.options.lsq12_likeFile 
     lsq12module = lsq12.FullLSQ12(self.inputs,
                                   self.dirs.lsq12Dir,
                                   likeFile=lsq12LikeFH,
                                   maxPairs=self.options.lsq12_max_pairs,
                                   lsq12_protocol=self.options.lsq12_protocol,
                                   subject_matter=self.options.lsq12_subject_matter)
     lsq12module.iterate()
     self.p.addPipeline(lsq12module.p)
     self.lsq12Params = lsq12module.lsq12Params
     if lsq12module.lsq12AvgFH.getMask()== None:
         if self.initModel:
             lsq12module.lsq12AvgFH.setMask(self.initModel[0].getMask())
     if not self.avgPrefix:
         self.avgPrefix = self.options.pipeline_name
     nlinModule = nlin.initializeAndRunNLIN(self.dirs.lsq12Dir,
                                            self.inputs,
                                            self.dirs.nlinDir,
                                            avgPrefix=self.avgPrefix, 
                                            createAvg=False,
                                            targetAvg=lsq12module.lsq12AvgFH,
                                            nlin_protocol=self.options.nlin_protocol,
                                            reg_method=self.options.reg_method)
     self.p.addPipeline(nlinModule.p)
     self.nlinFH = nlinModule.nlinAverages[-1]
     self.nlinParams = nlinModule.nlinParams
     self.initialTarget = nlinModule.initialTarget
     # Now we need the full transform to go back to LSQ6 space
     for i in self.inputs:
         linXfm = lsq12module.lsq12AvgXfms[i]
         nlinXfm = i.getLastXfm(self.nlinFH)
         outXfm = st.createOutputFileName(i, nlinXfm, "transforms", "_with_additional.xfm")
         xc = ma.xfmConcat([linXfm, nlinXfm], outXfm, fh.logFromFile(i.logDir, outXfm))
         self.p.addStage(xc)
         i.addAndSetXfmToUse(self.nlinFH, outXfm)
Ejemplo n.º 15
0
 def statsAndConcat(self, s, i, count, beforeAvg=True):
     """Construct array to common space for this timepoint.
        This builds upon arrays from previous calls."""
     if beforeAvg:
         xfm = s[i].getLastXfm(s[i+1]) 
     else:
         xfm = s[i].getLastXfm(s[i-1])
     """Set this transform as last xfm from input to nlin and calculate nlin to s[i] stats"""
     if self.nlinFH:
         self.xfmToCommon.insert(0, xfm)
         """ Concat transforms to get xfmToCommon and calculate statistics 
             Note that inverted transform, which is what we want, is calculated in
             the statistics module. """
         xtc = fh.createBaseName(s[i].transformsDir, s[i].basename + "_to_" + self.commonName + ".xfm")
         xc = ma.xfmConcat(self.xfmToCommon, xtc, fh.logFromFile(s[i].logDir, xtc))
         self.p.addStage(xc)
         s[i].addAndSetXfmToUse(self.nlinFH, xtc)
         self.statsCalculation(s[i], self.nlinFH, xfm=None, useChainStats=False)
     else:
         xtc=None
     """Calculate i to i+1 stats for all but final timePoint"""
     if count - i > 1:
         self.statsCalculation(s[i], s[i+1], xfm=xtc, useChainStats=True)
Ejemplo n.º 16
0
    def buildPipeline(self):
        lsq12LikeFH = None 
        resolutionForLSQ12 = None
        if self.initModel:
            lsq12LikeFH = self.initModel[0]
        elif self.options.lsq12_likeFile: 
            lsq12LikeFH = self.options.lsq12_likeFile 
        
        if lsq12LikeFH == None and self.options.lsq12_subject_matter == None and self.providedResolution == None:
            print("\nError: the FullIterativeLSQ12Nlin module was called without specifying either an initial model, nor an lsq12_subject_matter. Currently that means that the code can not determine the resolution at which the registrations should be run. Please specify one of the two. Exiting\n")
            sys.exit()
        
        if not (lsq12LikeFH == None):
            resolutionForLSQ12 = rf.returnFinestResolution(lsq12LikeFH)

        if resolutionForLSQ12 == None and self.providedResolution == None:
            print("\nError: the resolution at which the LSQ12 and the NLIN registration should be run could not be determined from either the initial model nor the LSQ12 like file. Please provide the fileResolution to the FullIterativeLSQ12Nlin module. Exiting\n")
            sys.exit()
        
        if resolutionForLSQ12 == None and self.providedResolution:
            resolutionForLSQ12 = self.providedResolution
        
        lsq12module = lsq12.FullLSQ12(self.inputs,
                                      self.dirs.lsq12Dir,
                                      queue_type=self.options.queue_type,
                                      likeFile=lsq12LikeFH,
                                      maxPairs=self.options.lsq12_max_pairs,
                                      lsq12_protocol=self.options.lsq12_protocol,
                                      subject_matter=self.options.lsq12_subject_matter,
                                      resolution=resolutionForLSQ12)
        lsq12module.iterate()
        self.p.addPipeline(lsq12module.p)
        self.lsq12Params = lsq12module.lsq12Params
        if lsq12module.lsq12AvgFH.getMask()== None:
            if self.initModel:
                lsq12module.lsq12AvgFH.setMask(self.initModel[0].getMask())
        if not self.avgPrefix:
            self.avgPrefix = self.options.pipeline_name
        # same as in MBM.py:
        # for now we can use the same resolution for the NLIN stages as we did for the 
        # LSQ12 stage. At some point we should look into the subject matter option...
        nlinModule = nlin.initializeAndRunNLIN(self.dirs.lsq12Dir,
                                               self.inputs,
                                               self.dirs.nlinDir,
                                               avgPrefix=self.avgPrefix, 
                                               createAvg=False,
                                               targetAvg=lsq12module.lsq12AvgFH,
                                               nlin_protocol=self.options.nlin_protocol,
                                               reg_method=self.options.reg_method,
                                               resolution=resolutionForLSQ12)
        self.p.addPipeline(nlinModule.p)
        self.nlinFH = nlinModule.nlinAverages[-1]
        self.nlinParams = nlinModule.nlinParams
        self.initialTarget = nlinModule.initialTarget
        # Now we need the full transform to go back to LSQ6 space
        for i in self.inputs:
            linXfm = lsq12module.lsq12AvgXfms[i]
            nlinXfm = i.getLastXfm(self.nlinFH)
            outXfm = st.createOutputFileName(i, nlinXfm, "transforms", "_with_additional.xfm")
            xc = ma.xfmConcat([linXfm, nlinXfm], outXfm, fh.logFromFile(i.logDir, outXfm))
            self.p.addStage(xc)
            i.addAndSetXfmToUse(self.nlinFH, outXfm)
Ejemplo n.º 17
0
 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