Ejemplo n.º 1
0
 def test_GroupAdjointAction(self, disp=False):
     hM = common.RandField(self.sz,
                           nSig=5.0,
                           gSig=4.0,
                           mType=ca.MEM_HOST,
                           sp=self.imSp)
     hV = common.RandField(self.sz,
                           nSig=5.0,
                           gSig=4.0,
                           mType=ca.MEM_HOST,
                           sp=self.imSp)
     hPhi = common.RandField(self.sz,
                             nSig=5.0,
                             gSig=4.0,
                             mType=ca.MEM_HOST,
                             sp=self.imSp)
     tmp = ca.Field3D(self.grid, ca.MEM_HOST)
     # compute < m, Ad_\phi v >
     ca.Ad(tmp, hPhi, hV)
     rhs = ca.Dot(tmp, hM)
     # compute < Ad^*_\phi m,  v >
     ca.CoAd(tmp, hPhi, hM)
     lhs = ca.Dot(tmp, hV)
     #print "a=%f b=%f" % (rhs, lhs)
     self.assertLess(abs(rhs - lhs), 2e-6)
def MatchingImageMomentaComputeEnergy(geodesicState, m0, J1, n1):
    vecEnergy = 0.0
    imageMatchEnergy = 0.0
    momentaMatchEnergy = 0.0

    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()

    imdiff = ca.ManagedImage3D(grid, mType)
    vecdiff = ca.ManagedField3D(grid, mType)

    # image match energy
    ca.ApplyH(imdiff, geodesicState.J0, geodesicState.rhoinv)
    ca.Sub_I(imdiff, J1)
    imageMatchEnergy = 0.5 * ca.Sum2(imdiff) / (
        float(geodesicState.p0.nVox()) * geodesicState.Sigma *
        geodesicState.Sigma * geodesicState.SigmaIntercept *
        geodesicState.SigmaIntercept)  # save for use in intercept energy term

    # momenta match energy
    ca.CoAd(geodesicState.p, geodesicState.rhoinv, m0)
    ca.Sub_I(geodesicState.p, n1)
    ca.Copy(vecdiff, geodesicState.p)  # save for use in slope energy term
    geodesicState.diffOp.applyInverseOperator(geodesicState.p)
    momentaMatchEnergy = ca.Dot(vecdiff, geodesicState.p) / (
        float(geodesicState.p0.nVox()) * geodesicState.SigmaSlope *
        geodesicState.SigmaSlope)

    # vector energy. p is used as scratch variable
    ca.Copy(geodesicState.p, geodesicState.p0)
    geodesicState.diffOp.applyInverseOperator(geodesicState.p)
    vecEnergy = 0.5 * ca.Dot(geodesicState.p0, geodesicState.p) / (
        float(geodesicState.p0.nVox()) * geodesicState.SigmaIntercept *
        geodesicState.SigmaIntercept)

    return (vecEnergy, imageMatchEnergy, momentaMatchEnergy)
def MatchingImageMomentaWriteOuput(cf, geodesicState, EnergyHistory, m0, n1):
    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()

    # save momenta for the gedoesic
    common.SaveITKField(geodesicState.p0, cf.io.outputPrefix + "p0.mhd")

    # save matched momenta for the geodesic
    if cf.vectormomentum.matchImOnly:
        m0 = common.LoadITKField(cf.study.m, mType)

    ca.CoAd(geodesicState.p, geodesicState.rhoinv, m0)
    common.SaveITKField(geodesicState.p, cf.io.outputPrefix + "m1.mhd")

    # momenta match energy
    if cf.vectormomentum.matchImOnly:
        vecdiff = ca.ManagedField3D(grid, mType)
        ca.Sub_I(geodesicState.p, n1)
        ca.Copy(vecdiff, geodesicState.p)
        geodesicState.diffOp.applyInverseOperator(geodesicState.p)
        momentaMatchEnergy = ca.Dot(vecdiff, geodesicState.p) / (
            float(geodesicState.p0.nVox()) * geodesicState.SigmaSlope *
            geodesicState.SigmaSlope)
        # save energy
        energyFilename = cf.io.outputPrefix + "testMomentaMatchEnergy.csv"
        with open(energyFilename, 'w') as f:
            print >> f, momentaMatchEnergy

    # save matched image for the geodesic
    tempim = ca.ManagedImage3D(grid, mType)
    ca.ApplyH(tempim, geodesicState.J0, geodesicState.rhoinv)
    common.SaveITKImage(tempim, cf.io.outputPrefix + "I1.mhd")

    # save energy
    energyFilename = cf.io.outputPrefix + "energy.csv"
    MatchingImageMomentaWriteEnergyHistoryToFile(EnergyHistory, energyFilename)
def MatchingImageMomentaPlots(cf,
                              geodesicState,
                              tDiscGeodesic,
                              EnergyHistory,
                              m0,
                              J1,
                              n1,
                              writeOutput=True):
    """
    Do some summary plots for MatchingImageMomenta
    """

    #ENERGY
    fig = plt.figure(1)
    plt.clf()
    fig.patch.set_facecolor('white')

    TE = [row[0] for row in EnergyHistory]
    VE = [row[1] for row in EnergyHistory]
    IE = [row[2] for row in EnergyHistory]
    ME = [row[3] for row in EnergyHistory]
    plt.subplot(2, 2, 1)
    plt.plot(TE)
    plt.title('Total Energy')
    plt.hold(False)
    plt.subplot(2, 2, 2)
    plt.plot(VE)
    plt.title('Vector Energy')
    plt.hold(False)
    plt.subplot(2, 2, 3)
    plt.plot(IE)
    plt.title('Image Match Energy')
    plt.hold(False)
    plt.subplot(2, 2, 4)
    plt.plot(ME)
    plt.title('Momenta Match Energy')
    plt.hold(False)
    plt.draw()
    plt.show()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'energy.pdf')

    # GEODESIC INITIAL CONDITIONS and RHO and RHO inv
    CAvmHGMCommon.HGMIntegrateGeodesic(geodesicState.p0, geodesicState.s,
                                       geodesicState.diffOp, geodesicState.p,
                                       geodesicState.rho, geodesicState.rhoinv,
                                       tDiscGeodesic, geodesicState.Ninv,
                                       geodesicState.integMethod)

    fig = plt.figure(2)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(2, 2, 1)
    display.DispImage(geodesicState.J0,
                      'J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.subplot(2, 2, 2)
    ca.ApplyH(geodesicState.J, geodesicState.J0, geodesicState.rhoinv)
    display.DispImage(geodesicState.J,
                      'J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)

    plt.subplot(2, 2, 3)
    display.GridPlot(geodesicState.rhoinv,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho^{-1}')
    plt.subplot(2, 2, 4)
    display.GridPlot(geodesicState.rho,
                     every=cf.io.quiverEvery,
                     color='k',
                     sliceIdx=cf.io.plotSlice,
                     isVF=False)
    plt.axis('equal')
    plt.axis('off')
    plt.title('rho')
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'def.pdf')

    # MATCHING DIFFERENCE IMAGES
    grid = geodesicState.J0.grid()
    mType = geodesicState.J0.memType()
    imdiff = ca.ManagedImage3D(grid, mType)

    # Image matching
    ca.Copy(imdiff, geodesicState.J)
    ca.Sub_I(imdiff, J1)
    fig = plt.figure(3)
    plt.clf()
    fig.patch.set_facecolor('white')

    plt.subplot(1, 3, 1)
    display.DispImage(geodesicState.J0,
                      'Source J0',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 2)
    display.DispImage(J1, 'Target J1', newFig=False, sliceIdx=cf.io.plotSlice)
    plt.colorbar()

    plt.subplot(1, 3, 3)
    display.DispImage(imdiff,
                      'rho.J0-J1',
                      newFig=False,
                      sliceIdx=cf.io.plotSlice)
    plt.colorbar()
    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'diffImage.pdf')

    # Momenta matching
    if mType == ca.MEM_DEVICE:
        scratchV1 = ca.Field3D(grid, mType)
        scratchV2 = ca.Field3D(grid, mType)
        scratchV3 = ca.Field3D(grid, mType)
    else:
        scratchV1 = ca.ManagedField3D(grid, mType)
        scratchV2 = ca.ManagedField3D(grid, mType)
        scratchV3 = ca.ManagedField3D(grid, mType)

    fig = plt.figure(4)
    plt.clf()
    fig.patch.set_facecolor('white')
    ca.Copy(scratchV1, m0)
    scratchV1.toType(ca.MEM_HOST)
    m0_x, m0_y, m0_z = scratchV1.asnp()
    plt.subplot(2, 3, 1)
    plt.imshow(np.squeeze(m0_x))
    plt.colorbar()
    plt.title('X: Source m0 ')
    plt.subplot(2, 3, 4)
    plt.imshow(np.squeeze(m0_y))
    plt.colorbar()
    plt.title('Y: Source m0')

    ca.Copy(scratchV2, n1)
    scratchV2.toType(ca.MEM_HOST)
    n1_x, n1_y, n1_z = scratchV2.asnp()
    plt.subplot(2, 3, 2)
    plt.imshow(np.squeeze(n1_x))
    plt.colorbar()
    plt.title('X: Target n1')
    plt.subplot(2, 3, 5)
    plt.imshow(np.squeeze(n1_y))
    plt.colorbar()
    plt.title('Y: Target n1')

    ca.CoAd(scratchV3, geodesicState.rhoinv, m0)
    ca.Sub_I(scratchV3, n1)
    scratchV3.toType(ca.MEM_HOST)
    diff_x, diff_y, diff_z = scratchV3.asnp()
    plt.subplot(2, 3, 3)
    plt.imshow(np.squeeze(diff_x))
    plt.colorbar()
    plt.title('X: rho.m0-n1')
    plt.subplot(2, 3, 6)
    plt.imshow(np.squeeze(diff_y))
    plt.colorbar()
    plt.title('Y: rho.m0-n1')

    if cf.io.outputPrefix != None and writeOutput:
        plt.savefig(cf.io.outputPrefix + 'diffMomenta.pdf')

    del scratchV1, scratchV2, scratchV3
    del imdiff
def GeodesicShooting(cf):

    # prepare output directory
    common.Mkdir_p(os.path.dirname(cf.io.outputPrefix))

    # Output loaded config
    if cf.io.outputPrefix is not None:
        cfstr = Config.ConfigToYAML(GeodesicShootingConfigSpec, cf)
        with open(cf.io.outputPrefix + "parsedconfig.yaml", "w") as f:
            f.write(cfstr)

    mType = ca.MEM_DEVICE if cf.useCUDA else ca.MEM_HOST
    #common.DebugHere()
    I0 = common.LoadITKImage(cf.study.I0, mType)
    m0 = common.LoadITKField(cf.study.m0, mType)
    grid = I0.grid()

    ca.ThreadMemoryManager.init(grid, mType, 1)
    # set up diffOp
    if mType == ca.MEM_HOST:
        diffOp = ca.FluidKernelFFTCPU()
    else:
        diffOp = ca.FluidKernelFFTGPU()
    diffOp.setAlpha(cf.diffOpParams[0])
    diffOp.setBeta(cf.diffOpParams[1])
    diffOp.setGamma(cf.diffOpParams[2])
    diffOp.setGrid(grid)

    g = ca.Field3D(grid, mType)
    ginv = ca.Field3D(grid, mType)
    mt = ca.Field3D(grid, mType)
    It = ca.Image3D(grid, mType)
    t = [
        x * 1. / cf.integration.nTimeSteps
        for x in range(cf.integration.nTimeSteps + 1)
    ]
    checkpointinds = range(1, len(t))
    checkpointstates = [(ca.Field3D(grid, mType), ca.Field3D(grid, mType))
                        for idx in checkpointinds]

    scratchV1 = ca.Field3D(grid, mType)
    scratchV2 = ca.Field3D(grid, mType)
    scratchV3 = ca.Field3D(grid, mType)
    # scale momenta to shoot
    cf.study.scaleMomenta = float(cf.study.scaleMomenta)
    if abs(cf.study.scaleMomenta) > 0.000000:
        ca.MulC_I(m0, float(cf.study.scaleMomenta))
        CAvmCommon.IntegrateGeodesic(m0,t,diffOp, mt, g, ginv,\
                                     scratchV1,scratchV2,scratchV3,\
                                     keepstates=checkpointstates,keepinds=checkpointinds,
                                     Ninv=cf.integration.NIterForInverse, integMethod = cf.integration.integMethod)
    else:
        ca.Copy(It, I0)
        ca.Copy(mt, m0)
        ca.SetToIdentity(ginv)
        ca.SetToIdentity(g)

    # write output
    if cf.io.outputPrefix is not None:
        # scale back shotmomenta before writing
        if abs(cf.study.scaleMomenta) > 0.000000:
            ca.ApplyH(It, I0, ginv)
            ca.CoAd(mt, ginv, m0)
            ca.DivC_I(mt, float(cf.study.scaleMomenta))

        common.SaveITKImage(It, cf.io.outputPrefix + "I1.mhd")
        common.SaveITKField(mt, cf.io.outputPrefix + "m1.mhd")
        common.SaveITKField(ginv, cf.io.outputPrefix + "phiinv.mhd")
        common.SaveITKField(g, cf.io.outputPrefix + "phi.mhd")
        GeodesicShootingPlots(g, ginv, I0, It, cf)
        if cf.io.saveFrames:
            SaveFrames(checkpointstates, checkpointinds, I0, It, m0, mt, cf)
def SaveFrames(checkpointstates, checkpointinds, I0, It, m0, mt, cf):
    momentathresh = 0.00002
    common.Mkdir_p(os.path.dirname(cf.io.outputPrefix) + '/frames/')
    image_idx = 0
    fig = plt.figure(1, frameon=False)
    plt.clf()
    display.DispImage(I0,
                      '',
                      newFig=False,
                      cmap='gray',
                      dim=cf.io.plotSliceDim,
                      sliceIdx=cf.io.plotSlice)
    plt.draw()
    outfilename = cf.io.outputPrefix + '/frames/I' + str(image_idx).zfill(
        5) + '.png'
    fig.set_size_inches(4, 4)
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(2, frameon=False)
    plt.clf()
    temp = ca.Field3D(I0.grid(), I0.memType())
    ca.SetToIdentity(temp)
    common.DebugHere()
    CAvmCommon.MyGridPlot(temp,
                          every=cf.io.gridEvery,
                          color='k',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice,
                          isVF=False,
                          plotBase=False)
    #fig.patch.set_alpha(0)
    #fig.patch.set_visible(False)
    a = fig.gca()
    #a.set_frame_on(False)
    a.set_xticks([])
    a.set_yticks([])
    plt.axis('tight')
    plt.axis('image')
    plt.axis('off')
    plt.draw()
    fig.set_size_inches(4, 4)
    outfilename = cf.io.outputPrefix + '/frames/invdef' + str(image_idx).zfill(
        5) + '.png'
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(3, frameon=False)
    plt.clf()
    CAvmCommon.MyGridPlot(temp,
                          every=cf.io.gridEvery,
                          color='k',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice,
                          isVF=False,
                          plotBase=False)
    #fig.patch.set_alpha(0)
    #fig.patch.set_visible(False)
    a = fig.gca()
    #a.set_frame_on(False)
    a.set_xticks([])
    a.set_yticks([])
    plt.axis('tight')
    plt.axis('image')
    plt.axis('off')
    plt.draw()
    fig.set_size_inches(4, 4)
    outfilename = cf.io.outputPrefix + '/frames/def' + str(image_idx).zfill(
        5) + '.png'
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    fig = plt.figure(4, frameon=False)
    plt.clf()
    display.DispImage(I0,
                      '',
                      newFig=False,
                      cmap='gray',
                      dim=cf.io.plotSliceDim,
                      sliceIdx=cf.io.plotSlice)
    plt.hold('True')
    CAvmCommon.MyQuiver(m0,
                        dim=cf.io.plotSliceDim,
                        sliceIdx=cf.io.plotSlice,
                        every=cf.io.quiverEvery,
                        thresh=momentathresh,
                        scaleArrows=0.25,
                        arrowCol='r',
                        lineWidth=0.5,
                        width=0.005)
    plt.draw()

    plt.hold('False')

    outfilename = cf.io.outputPrefix + '/frames/m' + str(image_idx).zfill(
        5) + '.png'
    fig.set_size_inches(4, 4)
    plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

    for i in range(len(checkpointinds)):
        image_idx = image_idx + 1
        ca.ApplyH(It, I0, checkpointstates[i][1])
        fig = plt.figure(1, frameon=False)
        plt.clf()
        display.DispImage(It,
                          '',
                          newFig=False,
                          cmap='gray',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice)
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/I' + str(image_idx).zfill(
            5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        fig = plt.figure(2, frameon=False)
        plt.clf()
        CAvmCommon.MyGridPlot(checkpointstates[i][1],
                              every=cf.io.gridEvery,
                              color='k',
                              dim=cf.io.plotSliceDim,
                              sliceIdx=cf.io.plotSlice,
                              isVF=False,
                              plotBase=False)
        #fig.patch.set_alpha(0)
        #fig.patch.set_visible(False)
        a = fig.gca()
        #a.set_frame_on(False)
        a.set_xticks([])
        a.set_yticks([])
        plt.axis('tight')
        plt.axis('image')
        plt.axis('off')
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/invdef' + str(
            image_idx).zfill(5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        fig = plt.figure(3, frameon=False)
        plt.clf()
        CAvmCommon.MyGridPlot(checkpointstates[i][0],
                              every=cf.io.gridEvery,
                              color='k',
                              dim=cf.io.plotSliceDim,
                              sliceIdx=cf.io.plotSlice,
                              isVF=False,
                              plotBase=False)
        #fig.patch.set_alpha(0)
        #fig.patch.set_visible(False)
        a = fig.gca()
        #a.set_frame_on(False)
        a.set_xticks([])
        a.set_yticks([])
        plt.axis('tight')
        plt.axis('image')
        plt.axis('off')
        plt.draw()
        outfilename = cf.io.outputPrefix + '/frames/def' + str(
            image_idx).zfill(5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)

        ca.CoAd(mt, checkpointstates[i][1], m0)
        fig = plt.figure(4, frameon=False)
        plt.clf()
        display.DispImage(It,
                          '',
                          newFig=False,
                          cmap='gray',
                          dim=cf.io.plotSliceDim,
                          sliceIdx=cf.io.plotSlice)
        plt.hold('True')
        CAvmCommon.MyQuiver(mt,
                            dim=cf.io.plotSliceDim,
                            sliceIdx=cf.io.plotSlice,
                            every=cf.io.quiverEvery,
                            thresh=momentathresh,
                            scaleArrows=0.40,
                            arrowCol='r',
                            lineWidth=0.5,
                            width=0.005)
        plt.draw()
        plt.hold('False')
        outfilename = cf.io.outputPrefix + '/frames/m' + str(image_idx).zfill(
            5) + '.png'
        fig.set_size_inches(4, 4)
        plt.savefig(outfilename, bbox_inches='tight', pad_inches=0, dpi=100)