def setScale(scale): global curGrid scaleManager.set(scale) curGrid = scaleManager.getCurGrid() # since this is only 2D: curGrid.spacing().z = 1.0 resampler.setScaleLevel(scaleManager) diffOp.setAlpha(fluidParams[0]) diffOp.setBeta(fluidParams[1]) diffOp.setGamma(fluidParams[2]) diffOp.setGrid(curGrid) # downsample images I0.setGrid(curGrid) I1.setGrid(curGrid) if scaleManager.isLastScale(): ca.Copy(I0, I0Orig) ca.Copy(I1, I1Orig) else: resampler.downsampleImage(I0, I0Orig) resampler.downsampleImage(I1, I1Orig) if Mask != None: if scaleManager.isLastScale(): Mask.setGrid(curGrid) ca.Copy(Mask, MaskOrig) else: resampler.downsampleImage(Mask, MaskOrig) # initialize / upsample deformation if scaleManager.isFirstScale(): u.setGrid(curGrid) ca.SetMem(u, 0.0) else: resampler.updateVField(u) # set grids gI.setGrid(curGrid) Idef.setGrid(curGrid) diff.setGrid(curGrid) gU.setGrid(curGrid) scratchI.setGrid(curGrid) scratchV.setGrid(curGrid)
def SetScale(scale): '''Scale Management for Multiscale''' scaleManager.set(scale) resampler.setScaleLevel(scaleManager) curGrid = scaleManager.getCurGrid() curGrid.spacing().z = 1 # Because only 2D print 'Inside setScale(). Current grid is ', curGrid if scaleManager.isLastScale(): print 'Inside setScale(): **Last Scale**' if scaleManager.isFirstScale(): print 'Inside setScale(): **First Scale**' scratchISrc.setGrid(curGrid) scratchITar.setGrid(curGrid) scratchI.setGrid(curGrid) compF.setGrid(curGrid) idConf.study.I0 = ca.Image3D(curGrid, memT) idConf.study.I1 = ca.Image3D(curGrid, memT) if scaleManager.isLastScale(): s = config.sigBlur[scaleList.index(sc)] r = config.kerBlur[scaleList.index(sc)] gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r), ca.Vec3Di(s, s, s)) gausFilt.filter(scratchITar, I_tar, temp) gausFilt.filter(scratchI, I_src, temp) # ca.Copy(scratchI, I_src) # ca.Copy(scratchITar, I_tar) else: s = config.sigBlur[scaleList.index(sc)] r = config.kerBlur[scaleList.index(sc)] gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r), ca.Vec3Di(s, s, s)) gausFilt.filter(I_tar_blur, I_tar, temp) gausFilt.filter(I_src_blur, I_src, temp) resampler.downsampleImage(scratchI, I_src_blur) resampler.downsampleImage(scratchITar, I_tar_blur) if scaleManager.isFirstScale(): scratchF.setGrid(curGrid) scratchITar.setGrid(curGrid) ca.SetToIdentity(scratchF) ca.ApplyH(scratchISrc, scratchI, scratchF) else: compF.setGrid(scratchF.grid()) ca.ComposeHH(compF, scratchF, h) resampler.updateHField(scratchF) resampler.updateHField(compF) ca.Copy(scratchF, compF) ca.ApplyH(scratchISrc, scratchI, compF)
def ComposeDef(V, t, asVField=False, inverse=False, scratchV1=None, scratchV2=None): """ Takes an array of Field3Ds and returns a Field3Ds containting the vectors Composed to non-integer time t """ vlen = len(V) grid = V[0].grid() mType = V[0].memType() # just clamp to final time if t > vlen: t = vlen t_int = int(math.floor(t)) t_frac = t - t_int h = core.Field3D(grid, mType) if scratchV1 is None: scratchV1 = core.Field3D(grid, mType) core.SetToIdentity(h) for s in range(t_int): if inverse: core.ComposeHVInv(scratchV1, h, V[s]) else: core.ComposeVH(scratchV1, V[s], h) h.swap(scratchV1) if t_frac != 0.0: if scratchV2 is None: scratchV2 = core.Field3D(grid, mType) core.Copy(scratchV2, V[t_int]) core.MulC_I(scratchV2, core.Vec3Df(t_frac, t_frac, t_frac)) if inverse: core.ComposeHVInv(scratchV1, h, scratchV2) else: core.ComposeVH(scratchV1, scratchV2, h) core.Copy(h, scratchV1) if asVField: core.SetToIdentity(scratchV1) core.Sub_I(h, scratchV1) return h
def DispImage(im, title=None, sliceIdx=None, dim='z', cmap='gray', newFig=True, rng=None, t=False, log=False): # if this volume is not a slice already, extract a slice sz = im.size().tolist() if sz[common.DIMMAP[dim]] > 1: im = common.ExtractSliceIm(im, sliceIdx, dim) im.toType(core.MEM_HOST) # transfer to host memory if necessary if im.memType() == core.MEM_DEVICE: tmp = core.Image3D(im.grid(), core.MEM_HOST) core.Copy(tmp, im) im = tmp # create the figure if requested if newFig: if title is None: plt.figure() else: plt.figure(title) plt.clf() # set the range if rng is None: vmin = None vmax = None else: vmin = rng[0] vmax = rng[1] if log: norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) # convert to numpy array arr = np.squeeze(im.asnp().copy()) # transpose if requested if t: arr = arr.T # display plt.imshow(arr, cmap=cmap, vmin=vmin, vmax=vmax, norm=norm, interpolation='nearest') plt.axis('tight') plt.axis('image') if title is not None: plt.title(title) plt.xticks([]) plt.yticks([]) plt.draw()
def Reduce(A, hA, op=None): """Reduce PyCA Image3D or Field3D over MPI A can live anywhere but hA needs to be of mType MEM_HOST """ if not hasMPI: raise Exception("mpi4py required for Reduce operations: not found") if op is None: op = MPI.SUM if A.memType() == ca.MEM_HOST: # can do this in place without using hA if isinstance(A, ca.Image3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.asnp(), op=op) elif isinstance(A, ca.Field3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.x_asnp(), op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.y_asnp(), op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.z_asnp(), op=op) else: raise Exception('Can only reduce Image3D and Field3D') else: # will need some uploading and downloading assert(hA.memType() == ca.MEM_HOST) # make sure we can actually use hA ca.Copy(hA, A) # download if isinstance(A, ca.Image3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.asnp(), op=op) elif isinstance(A, ca.Field3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.x_asnp(), op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.y_asnp(), op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.z_asnp(), op=op) else: raise Exception('Can only reduce Image3D and Field3D') ca.Copy(A, hA) # upload
def Reduce(A, hA, op=MPI.SUM): """Reduce PyCA Image3D or Field3D over MPI A can live anywhere but hA needs to be of mType MEM_HOST """ if A.memType() == ca.MEM_HOST: # can do this in place without using hA if isinstance(A, ca.Field3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.asnp()[0], op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.asnp()[1], op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.asnp()[2], op=op) else: MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, A.asnp(), op=op) else: # will need some uploading and downloading assert (hA.memType() == ca.MEM_HOST ) # make sure we can actually use hA ca.Copy(hA, A) # download if isinstance(A, ca.Field3D): MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.asnp()[0], op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.asnp()[1], op=op) MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.asnp()[2], op=op) else: MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, hA.asnp(), op=op) ca.Copy(A, hA) # upload
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 MatchingGradient(p): # shoot the geodesic forward CAvmCommon.IntegrateGeodesic(p.m0,p.t,p.diffOp, \ p.m, p.g, p.ginv,\ p.scratchV1, p.scratchV2,p. scratchV3,\ p.checkpointstates, p.checkpointinds,\ Ninv=p.nInv, integMethod = p.integMethod, RK4=p.scratchV4,scratchG=p.scratchV5) endidx = p.checkpointinds.index(len(p.t)-1) # compute residual image ca.ApplyH(p.residualIm,p.I0,p.ginv) ca.Sub_I(p.residualIm, p.I1) # while we have residual, save the image energy IEnergy = ca.Sum2(p.residualIm)/(2*p.sigma*p.sigma*float(p.I0.nVox())) ca.DivC_I(p.residualIm, p.sigma*p.sigma) # gradient at measurement # integrate backward CAvmCommon.IntegrateAdjoints(p.Iadj,p.madj,\ p.I,p.m,p.Iadjtmp, p.madjtmp,p.scratchV1,\ p.scratchV2,p.scratchV3,\ p.I0,p.m0,\ p.t, p.checkpointstates, p.checkpointinds,\ [p.residualIm], [endidx],\ p.diffOp, p.integMethod, p.nInv, \ scratchV3=p.scratchV7, scratchV4=p.g,scratchV5=p.ginv,scratchV6=p.scratchV8, scratchV7=p.scratchV9, \ scratchV8=p.scratchV10,scratchV9=p.scratchV11,\ RK4=p.scratchV4, scratchG=p.scratchV5, scratchGinv=p.scratchV6) # compute gradient ca.Copy(p.scratchV1, p.m0) p.diffOp.applyInverseOperator(p.scratchV1) # while we have velocity, save the vector energy VEnergy = 0.5*ca.Dot(p.m0,p.scratchV1)/float(p.I0.nVox()) ca.Sub_I(p.scratchV1, p.madj) #p.diffOp.applyOperator(p.scratchV1) return (p.scratchV1, VEnergy, IEnergy)
def JacDetPlot(vf, title='Jac. Det.', jd_max=10.0, cmap='PRGn', nonpos_clr=(1.0, 0.0, 0.0, 1.0), sliceIdx=None, dim='z', isVF=True, newFig=False): """ Plot the jacobian determinant using logmapped colors, and setting zero or negative values to 'nonpos_clr'. jd_max is the maximum value to display without clamping, and also defines the min value as 1.0/jd_max to assure 1.0 is centered in the colormap. If vf is a vector field, compute the jacobian determinant. If it is an Image3D, assume it is the jacobian determinant to be plotted. """ if common.IsField3D(vf): grid = vf.grid() mType = vf.memType() h = core.ManagedField3D(grid, mType) jacdet = core.ManagedImage3D(grid, mType) core.Copy(h, vf) if isVF: core.VtoH_I(h) core.JacDetH(jacdet, h) elif common.IsImage3D(vf): jacdet = vf else: raise Exception('unknown input type to JacDetPlot, %s'%\ str(type(vf))) jd_cmap = JacDetCMap(jd_max=jd_max, cmap=cmap, nonpos_clr=nonpos_clr) DispImage(jacdet, title=title, sliceIdx=sliceIdx, dim=dim, rng=[1.0/jd_max, jd_max], cmap=jd_cmap, log=True, newFig=newFig)
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 RigidReg( Is, It, theta_step=.0001, t_step=.01, a_step=0, maxIter=350, plot=True, origin=None, theta=0, # only applies for 2D t=None, # only applies for 2D Ain=np.matrix(np.identity(3))): Idef = ca.Image3D(It.grid(), It.memType()) gradIdef = ca.Field3D(It.grid(), It.memType()) h = ca.Field3D(It.grid(), It.memType()) ca.SetToIdentity(h) x = ca.Image3D(It.grid(), It.memType()) y = ca.Image3D(It.grid(), It.memType()) DX = ca.Image3D(It.grid(), It.memType()) DY = ca.Image3D(It.grid(), It.memType()) diff = ca.Image3D(It.grid(), It.memType()) scratchI = ca.Image3D(It.grid(), It.memType()) ca.Copy(x, h, 0) ca.Copy(y, h, 1) if origin is None: origin = [(Is.grid().size().x + 1) / 2.0, (Is.grid().size().y + 1) / 2.0, (Is.grid().size().z + 1) / 2.0] x -= origin[0] y -= origin[1] numel = It.size().x * It.size().y * It.size().z immin, immax = ca.MinMax(It) imrng = max(immax - immin, .01) t_step /= numel * imrng theta_step /= numel * imrng a_step /= numel * imrng energy = [] a = 1 if cc.Is3D(Is): if theta: print "theta is not utilized in 3D registration" z = ca.Image3D(It.grid(), It.memType()) DZ = ca.Image3D(It.grid(), It.memType()) ca.Copy(z, h, 2) z -= origin[2] A = np.matrix(np.identity(4)) cc.ApplyAffineReal(Idef, Is, A) # cc.ApplyAffine(Idef, Is, A, origin) t = [0, 0, 0] for i in xrange(maxIter): ca.Sub(diff, Idef, It) ca.Gradient(gradIdef, Idef) ca.Copy(DX, gradIdef, 0) ca.Copy(DY, gradIdef, 1) ca.Copy(DZ, gradIdef, 2) # take gradient step for the translation ca.Mul(scratchI, DX, diff) t[0] += t_step * ca.Sum(scratchI) ca.Mul(scratchI, DY, diff) t[1] += t_step * ca.Sum(scratchI) ca.Mul(scratchI, DZ, diff) t[2] += t_step * ca.Sum(scratchI) A[0, 3] = t[0] A[1, 3] = t[1] A[2, 3] = t[2] if a_step > 0: DX *= x DY *= y DZ *= z DZ += DX DZ += DY DZ *= diff d_a = a_step * ca.Sum(DZ) a_prev = a a += d_a # multiplying by a/a_prev is equivalent to adding (a-aprev) A = A * np.matrix([[a / a_prev, 0, 0, 0], [ 0, a / a_prev, 0, 0 ], [0, 0, a / a_prev, 0], [0, 0, 0, 1]]) # Z rotation ca.Copy(DX, gradIdef, 0) ca.Copy(DY, gradIdef, 1) DX *= y ca.Neg_I(DX) DY *= x ca.Add(scratchI, DX, DY) scratchI *= diff theta = -theta_step * ca.Sum(scratchI) # % Recalculate A A = A * np.matrix( [[np.cos(theta), np.sin(theta), 0, 0], [-np.sin(theta), np.cos(theta), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # Y rotation ca.Copy(DX, gradIdef, 0) ca.Copy(DZ, gradIdef, 2) DX *= z ca.Neg_I(DX) DZ *= x ca.Add(scratchI, DX, DZ) scratchI *= diff theta = -theta_step * ca.Sum(scratchI) # % Recalculate A A = A * np.matrix( [[np.cos(theta), 0, np.sin(theta), 0], [0, 1, 0, 0], [-np.sin(theta), 0, np.cos(theta), 0], [0, 0, 0, 1]]) # X rotation ca.Copy(DY, gradIdef, 1) ca.Copy(DZ, gradIdef, 2) DY *= z ca.Neg_I(DY) DZ *= y ca.Add(scratchI, DY, DZ) scratchI *= diff theta = -theta_step * ca.Sum(scratchI) # Recalculate A A = A * np.matrix( [[1, 0, 0, 0], [0, np.cos(theta), np.sin(theta), 0], [0, -np.sin(theta), np.cos(theta), 0], [0, 0, 0, 1]]) cc.ApplyAffineReal(Idef, Is, A) # cc.ApplyAffine(Idef, Is, A, origin) # % display Energy (and other figures) at the end energy.append(ca.Sum2(diff)) if (i == maxIter - 1) or (i > 75 and abs(energy[-1] - energy[-50]) < immax): cd.DispImage(diff, title='Difference Image', colorbar=True) plt.figure() plt.plot(energy) cd.DispImage(Idef, title='Deformed Image') break elif cc.Is2D(Is): # theta = 0 if t is None: t = [0, 0] # A = np.array([[a*np.cos(theta), np.sin(theta), t[0]], # [-np.sin(theta), a*np.cos(theta), t[1]], # [0, 0, 1]]) A = np.copy(Ain) cc.ApplyAffineReal(Idef, Is, A) # ca.Copy(Idef, Is) for i in xrange(1, maxIter): # [FX,FY] = gradient(Idef) ca.Sub(diff, Idef, It) ca.Gradient(gradIdef, Idef) ca.Copy(DX, gradIdef, 0) ca.Copy(DY, gradIdef, 1) # take gradient step for the translation ca.Mul(scratchI, DX, diff) t[0] += t_step * ca.Sum(scratchI) ca.Mul(scratchI, DY, diff) t[1] += t_step * ca.Sum(scratchI) # take gradient step for the rotation theta if a_step > 0: # d/da DX *= x DY *= y DY += DX DY *= diff d_a = a_step * ca.Sum(DY) a += d_a # d/dtheta ca.Copy(DX, gradIdef, 0) ca.Copy(DY, gradIdef, 1) DX *= y ca.Neg_I(DX) DY *= x ca.Add(scratchI, DX, DY) scratchI *= diff d_theta = theta_step * ca.Sum(scratchI) theta -= d_theta # Recalculate A, Idef A = np.matrix([[a * np.cos(theta), np.sin(theta), t[0]], [-np.sin(theta), a * np.cos(theta), t[1]], [0, 0, 1]]) A = Ain * A cc.ApplyAffineReal(Idef, Is, A) # cc.ApplyAffine(Idef, Is, A, origin) # % display Energy (and other figures) at the end energy.append(ca.Sum2(diff)) if (i == maxIter - 1) or (i > 75 and abs(energy[-1] - energy[-50]) < immax): if i == maxIter - 1: print "not converged in ", maxIter, " Iterations" if plot: cd.DispImage(diff, title='Difference Image', colorbar=True) plt.figure() plt.plot(energy) cd.DispImage(Idef, title='Deformed Image') break return A
def Fragmenter(): tmpOb = Config.Load( frgSpec, pth.expanduser( '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/section_{1}_frag0.yaml' .format(secOb.mkyNum, secOb.secNum))) dictBuild = {} #Load in the whole image so that the fragment can cropped out ssiSrc, bfiSrc, ssiMsk, bfiMsk = Loader(tmpOb, ca.MEM_HOST) #Because some of the functions only woth with gray images bfiGry = ca.Image3D(bfiSrc.grid(), bfiSrc.memType()) ca.Copy(bfiGry, bfiSrc, 1) lblSsi, _ = ndimage.label(np.squeeze(ssiMsk.asnp()) > 0) lblBfi, _ = ndimage.label(np.squeeze(bfiMsk.asnp()) > 0) seedPt = np.squeeze(pp.LandmarkPicker([lblBfi, lblSsi])) subMskBfi = common.ImFromNPArr(lblBfi == lblBfi[seedPt[0, 0], seedPt[0, 1]].astype('int8'), sp=bfiSrc.spacing(), orig=bfiSrc.origin()) subMskSsi = common.ImFromNPArr(lblSsi == lblSsi[seedPt[1, 0], seedPt[1, 1]].astype('int8'), sp=ssiSrc.spacing(), orig=ssiSrc.origin()) bfiGry *= subMskBfi bfiSrc *= subMskBfi ssiSrc *= subMskSsi #Pick points that are the bounding box of the desired subvolume corners = np.array( pp.LandmarkPicker( [np.squeeze(bfiGry.asnp()), np.squeeze(ssiSrc.asnp())])) bfiCds = corners[:, 0] ssiCds = corners[:, 1] #Extract the region from the source images bfiRgn = cc.SubVol(bfiSrc, xrng=[bfiCds[0, 0], bfiCds[1, 0]], yrng=[bfiCds[0, 1], bfiCds[1, 1]]) ssiRgn = cc.SubVol(ssiSrc, xrng=[ssiCds[0, 0], ssiCds[1, 0]], yrng=[ssiCds[0, 1], ssiCds[1, 1]]) #Extract the region from the mask images rgnMskSsi = cc.SubVol(subMskSsi, xrng=[ssiCds[0, 0], ssiCds[1, 0]], yrng=[ssiCds[0, 1], ssiCds[1, 1]]) rgnMskBfi = cc.SubVol(subMskBfi, xrng=[bfiCds[0, 0], bfiCds[1, 0]], yrng=[bfiCds[0, 1], bfiCds[1, 1]]) dictBuild['rgnBfi'] = np.divide( bfiCds, np.array(bfiSrc.size().tolist()[0:2], 'float')).tolist() dictBuild['rgnSsi'] = np.divide( ssiCds, np.array(ssiSrc.size().tolist()[0:2], 'float')).tolist() #Check the output directory for the source files of the fragment if not pth.exists( pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum))) if not pth.exists( pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum))) #Check the output directory for the mask files of the fragment if not pth.exists( pth.expanduser(secOb.ssiMskPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.ssiMskPath + 'frag{0}'.format(frgNum))) if not pth.exists( pth.expanduser(secOb.bfiMskPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.bfiMskPath + 'frag{0}'.format(frgNum))) dictBuild[ 'ssiSrcName'] = 'frag{0}/M{1}_01_ssi_section_{2}_frag1.tif'.format( frgNum, secOb.mkyNum, secOb.secNum) dictBuild[ 'bfiSrcName'] = 'frag{0}/M{1}_01_bfi_section_{2}_frag1.mha'.format( frgNum, secOb.mkyNum, secOb.secNum) dictBuild[ 'ssiMskName'] = 'frag{0}/M{1}_01_ssi_section_{2}_frag1_mask.tif'.format( frgNum, secOb.mkyNum, secOb.secNum) dictBuild[ 'bfiMskName'] = 'frag{0}/M{1}_01_bfi_section_{2}_frag1_mask.tif'.format( frgNum, secOb.mkyNum, secOb.secNum) #Write out the masked and cropped images so that they can be loaded from the YAML file #The BFI region needs to be saved as color and mha format so that the grid information is carried over. common.SaveITKImage( ssiRgn, pth.expanduser(secOb.ssiSrcPath + dictBuild['ssiSrcName'])) cc.WriteColorMHA( bfiRgn, pth.expanduser(secOb.bfiSrcPath + dictBuild['bfiSrcName'])) common.SaveITKImage( rgnMskSsi, pth.expanduser(secOb.ssiMskPath + dictBuild['ssiMskName'])) common.SaveITKImage( rgnMskBfi, pth.expanduser(secOb.bfiMskPath + dictBuild['bfiMskName'])) frgOb = Config.MkConfig(dictBuild, frgSpec) updateFragOb(frgOb) return None
if SaveBW: cc.InsertSlice(BFIDef3D_BW, BFI_def_BW, sliceIdx) continue # Run IDiff on VE B/W Images MRI = common.ExtractSliceIm(MRI3D, sliceIdx) # Make Memory all fast MRI.toType(ca.MEM_DEVICE) BFI.toType(ca.MEM_DEVICE) # Standardize Grids MRI.setGrid(grid2D) BFI.setGrid(grid2D) MRI /= ca.Max(MRI) BFI_VE = ca.Image3D(grid2D, BFI.memType()) MRI_VE = ca.Image3D(grid2D, MRI.memType()) ca.Copy(MRI_VE, MRI) ca.Copy(BFI_VE, BFI) cc.SetRegionLTE(MRI_VE, MRI, 0.13, 1) MRI_VE *= -1 square = ca.Image3D(grid2D, BFI.memType()) cc.CreateRect(square, [0, 0], [440, 440]) BFI_VE *= square cc.VarianceEqualize_I(BFI_VE, sigma=5.0) cc.VarianceEqualize_I(MRI_VE, sigma=5.0) grid_orig = BFI_VE.grid().copy() grid_new = cc.MakeGrid(grid_orig.size(), [1, 1, 1], 'center') BFI_VE.setGrid(grid_new)
def ApplyAffine(Iout, Im, A, bg=ca.BACKGROUND_STRATEGY_PARTIAL_ZERO): '''Applies an Affine matrix A to an image Im using the Image3D grid (size, spacing, origin) of the two images (Input and Output) ''' # algorithm outline: Create a temporary large grid, then perform # real affine transforms here, then crop to be the size of the out grid ca.SetMem(Iout, 0.0) A = np.matrix(A) bigsize = [max(Iout.grid().size().x, Im.grid().size().x), max(Iout.grid().size().y, Im.grid().size().y), max(Iout.grid().size().z, Im.grid().size().z)] idgrid = ca.GridInfo(ca.Vec3Di(bigsize[0], bigsize[1], bigsize[2]), ca.Vec3Df(1, 1, 1), ca.Vec3Df(0, 0, 0)) # newgrid = Iout.grid() # not a true copy!!!!! newgrid = ca.GridInfo(Iout.grid().size(), Iout.grid().spacing(), Iout.grid().origin()) mType = Iout.memType() Imbig = cc.PadImage(Im, bigsize) h = ca.Field3D(idgrid, mType) ca.SetToIdentity(h) if isinstance(Im, ca.Field3D): Ioutbig = ca.Field3D(idgrid, mType) else: Ioutbig = ca.Image3D(idgrid, mType) # note: x_real' = A*x_real; x_real' given (input grid) # solution: x_real = A^-1 * x_real # where x_real = x_index*spacing + origin # and x_real' = x_index'*spacing' + origin' # x_index' is really given, as is both spacings/origins # and we plug in the solution for x_index' into applyH if A.shape[1] == 3: # 2D affine matrix x = ca.Image3D(idgrid, mType) y = ca.Image3D(idgrid, mType) xnew = ca.Image3D(idgrid, mType) ynew = ca.Image3D(idgrid, mType) ca.Copy(x, h, 0) ca.Copy(y, h, 1) # convert x,y to world coordinates x *= Iout.grid().spacing().x y *= Iout.grid().spacing().y x += Iout.grid().origin().x y += Iout.grid().origin().y # Matrix Multiply (All in real coords) Ainv = A.I ca.MulC_Add_MulC(xnew, x, Ainv[0, 0], y, Ainv[0, 1]) ca.MulC_Add_MulC(ynew, x, Ainv[1, 0], y, Ainv[1, 1]) xnew += (Ainv[0, 2]) ynew += (Ainv[1, 2]) # xnew and ynew are now in real coords # convert back to index coordinates xnew -= Im.grid().origin().x ynew -= Im.grid().origin().y xnew /= Im.grid().spacing().x ynew /= Im.grid().spacing().y ca.SetToZero(h) ca.Copy(h, xnew, 0) ca.Copy(h, ynew, 1) elif A.shape[1] == 4: # 3D affine matrix x = ca.Image3D(idgrid, mType) y = ca.Image3D(idgrid, mType) z = ca.Image3D(idgrid, mType) xnew = ca.Image3D(idgrid, mType) ynew = ca.Image3D(idgrid, mType) znew = ca.Image3D(idgrid, mType) ca.Copy(x, h, 0) ca.Copy(y, h, 1) ca.Copy(z, h, 2) x *= Iout.grid().spacing().x y *= Iout.grid().spacing().y z *= Iout.grid().spacing().z x += Iout.grid().origin().x y += Iout.grid().origin().y z += Iout.grid().origin().z # Matrix Multiply (All in real coords) Ainv = A.I ca.MulC_Add_MulC(xnew, x, Ainv[0, 0], y, Ainv[0, 1]) ca.Add_MulC_I(xnew, z, Ainv[0, 2]) xnew += (Ainv[0, 3]) ca.MulC_Add_MulC(ynew, x, Ainv[1, 0], y, Ainv[1, 1]) ca.Add_MulC_I(ynew, z, Ainv[1, 2]) ynew += (Ainv[1, 3]) ca.MulC_Add_MulC(znew, x, Ainv[2, 0], y, Ainv[2, 1]) ca.Add_MulC_I(znew, z, Ainv[2, 2]) znew += (Ainv[2, 3]) # convert to index coordinates xnew -= Im.grid().origin().x ynew -= Im.grid().origin().y znew -= Im.grid().origin().z xnew /= Im.grid().spacing().x ynew /= Im.grid().spacing().y znew /= Im.grid().spacing().z ca.Copy(h, xnew, 0) ca.Copy(h, ynew, 1) ca.Copy(h, znew, 2) Imbig.setGrid(idgrid) ca.ApplyH(Ioutbig, Imbig, h, bg) # crop Ioutbig -> Iout ca.SubVol(Iout, Ioutbig, ca.Vec3Di(0, 0, 0)) Iout.setGrid(newgrid) # change back
def main(): # Extract the Monkey number and section number from the command line global frgNum global secOb mkyNum = sys.argv[1] secNum = sys.argv[2] frgNum = int(sys.argv[3]) write = True # if not os.path.exists(os.path.expanduser('~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml'.format(mkyNum,secNum))): # cf = initial(secNum, mkyNum) try: secOb = Config.Load( secSpec, pth.expanduser( '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml' .format(mkyNum, secNum))) except IOError as e: try: temp = Config.LoadYAMLDict(pth.expanduser( '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml' .format(mkyNum, secNum)), include=False) secOb = Config.MkConfig(temp, secSpec) except IOError: print 'It appears there is no configuration file for this section. Please initialize one and restart.' sys.exit() if frgNum == int(secOb.yamlList[frgNum][-6]): Fragmenter() try: secOb = Config.Load( secSpec, pth.expanduser( '~/korenbergNAS/3D_database/Working/configuration_files/SidescapeRelateBlockface/M{0}/section_{1}/include_configFile.yaml' .format(mkyNum, secNum))) except IOError: print 'It appeas that the include yaml file list does not match your fragmentation number. Please check them and restart.' sys.exit() if not pth.exists( pth.expanduser(secOb.ssiOutPath + 'frag{0}'.format(frgNum))): common.Mkdir_p( pth.expanduser(secOb.ssiOutPath + 'frag{0}'.format(frgNum))) if not pth.exists( pth.expanduser(secOb.bfiOutPath + 'frag{0}'.format(frgNum))): common.Mkdir_p( pth.expanduser(secOb.bfiOutPath + 'frag{0}'.format(frgNum))) if not pth.exists( pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.ssiSrcPath + 'frag{0}'.format(frgNum))) if not pth.exists( pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum))): os.mkdir(pth.expanduser(secOb.bfiSrcPath + 'frag{0}'.format(frgNum))) frgOb = Config.MkConfig(secOb.yamlList[frgNum], frgSpec) ssiSrc, bfiSrc, ssiMsk, bfiMsk = Loader(frgOb, ca.MEM_HOST) #Extract the saturation Image from the color iamge bfiHsv = common.FieldFromNPArr( matplotlib.colors.rgb_to_hsv( np.rollaxis(np.array(np.squeeze(bfiSrc.asnp())), 0, 3)), ca.MEM_HOST) bfiHsv.setGrid(bfiSrc.grid()) bfiSat = ca.Image3D(bfiSrc.grid(), bfiHsv.memType()) ca.Copy(bfiSat, bfiHsv, 1) #Histogram equalize, normalize and mask the blockface saturation image bfiSat = cb.HistogramEqualize(bfiSat, 256) bfiSat.setGrid(bfiSrc.grid()) bfiSat *= -1 bfiSat -= ca.Min(bfiSat) bfiSat /= ca.Max(bfiSat) bfiSat *= bfiMsk bfiSat.setGrid(bfiSrc.grid()) #Write out the blockface region after adjusting the colors with a format that supports header information if write: common.SaveITKImage( bfiSat, pth.expanduser(secOb.bfiSrcPath + 'frag{0}/M{1}_01_bfi_section_{2}_frag{0}_sat.nrrd'. format(frgNum, secOb.mkyNum, secOb.secNum))) #Set the sidescape grid relative to that of the blockface ssiSrc.setGrid(ConvertGrid(ssiSrc.grid(), bfiSat.grid())) ssiMsk.setGrid(ConvertGrid(ssiMsk.grid(), bfiSat.grid())) ssiSrc *= ssiMsk #Write out the sidescape masked image in a format that stores the header information if write: common.SaveITKImage( ssiSrc, pth.expanduser(secOb.ssiSrcPath + 'frag{0}/M{1}_01_ssi_section_{2}_frag{0}.nrrd'. format(frgNum, secOb.mkyNum, secOb.secNum))) #Update the image parameters of the sidescape image for future use frgOb.imSize = ssiSrc.size().tolist() frgOb.imOrig = ssiSrc.origin().tolist() frgOb.imSpac = ssiSrc.spacing().tolist() updateFragOb(frgOb) #Find the affine transform between the two fragments bfiAff, ssiAff, aff = Affine(bfiSat, ssiSrc, frgOb) updateFragOb(frgOb) #Write out the affine transformed images in a format that stores header information if write: common.SaveITKImage( bfiAff, pth.expanduser( secOb.bfiOutPath + 'frag{0}/M{1}_01_bfi_section_{2}_frag{0}_aff_ssi.nrrd'.format( frgNum, secOb.mkyNum, secOb.secNum))) common.SaveITKImage( ssiAff, pth.expanduser( secOb.ssiOutPath + 'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_aff_bfi.nrrd'.format( frgNum, secOb.mkyNum, secOb.secNum))) bfiVe = bfiAff.copy() ssiVe = ssiSrc.copy() cc.VarianceEqualize_I(bfiVe, sigma=frgOb.sigVarBfi, eps=frgOb.epsVar) cc.VarianceEqualize_I(ssiVe, sigma=frgOb.sigVarSsi, eps=frgOb.epsVar) #As of right now, the largest pre-computed FFT table is 2048, so resample onto that grid for registration regGrd = ConvertGrid( cc.MakeGrid(ca.Vec3Di(2048, 2048, 1), ca.Vec3Df(1, 1, 1), ca.Vec3Df(0, 0, 0)), ssiSrc.grid()) ssiReg = ca.Image3D(regGrd, ca.MEM_HOST) bfiReg = ca.Image3D(regGrd, ca.MEM_HOST) cc.ResampleWorld(ssiReg, ssiVe) cc.ResampleWorld(bfiReg, bfiVe) #Create the default configuration object for IDiff Matching and then set some parameters idCf = Config.SpecToConfig(IDiff.Matching.MatchingConfigSpec) idCf.compute.useCUDA = True idCf.io.outputPrefix = '/home/sci/blakez/IDtest/' #Run the registration ssiDef, phi = DefReg(ssiReg, bfiReg, frgOb, ca.MEM_DEVICE, idCf) #Turn the deformation into a displacement field so it can be applied to the large tif with C++ code affV = phi.copy() cc.ApplyAffineReal(affV, phi, np.linalg.inv(frgOb.affine)) ca.HtoV_I(affV) #Apply the found deformation to the input ssi ssiSrc.toType(ca.MEM_DEVICE) cc.HtoReal(phi) affPhi = phi.copy() ssiBfi = ssiSrc.copy() upPhi = ca.Field3D(ssiSrc.grid(), phi.memType()) cc.ApplyAffineReal(affPhi, phi, np.linalg.inv(frgOb.affine)) cc.ResampleWorld(upPhi, affPhi, bg=2) cc.ApplyHReal(ssiBfi, ssiSrc, upPhi) # ssiPhi = ca.Image3D(ssiSrc.grid(), phi.memType()) # upPhi = ca.Field3D(ssiSrc.grid(), phi.memType()) # cc.ResampleWorld(upPhi, phi, bg=2) # cc.ApplyHReal(ssiPhi, ssiSrc, upPhi) # ssiBfi = ssiSrc.copy() # cc.ApplyAffineReal(ssiBfi, ssiPhi, np.linalg.inv(frgOb.affine)) # #Apply affine to the deformation # affPhi = phi.copy() # cc.ApplyAffineReal(affPhi, phi, np.linalg.inv(frgOb.affine)) if write: common.SaveITKImage( ssiBfi, pth.expanduser( secOb.ssiOutPath + 'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_def_bfi.nrrd'.format( frgNum, secOb.mkyNum, secOb.secNum))) cc.WriteMHA( affPhi, pth.expanduser( secOb.ssiOutPath + 'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_to_bfi_real.mha'. format(frgNum, secOb.mkyNum, secOb.secNum))) cc.WriteMHA( affV, pth.expanduser( secOb.ssiOutPath + 'frag{0}/M{1}_01_ssi_section_{2}_frag{0}_to_bfi_disp.mha'. format(frgNum, secOb.mkyNum, secOb.secNum))) #Create the list of names that the deformation should be applied to # nameList = ['M15_01_0956_SideLight_DimLED_10x_ORG.tif', # 'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c1_ORG.tif', # 'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c2_ORG.tif', # 'M15_01_0956_TyrosineHydroxylase_Ben_10x_Stitching_c3_ORG.tif'] # appLarge(nameList, affPhi) common.DebugHere()
for i in xrange(1, 5): fname = imagedir + 'block' + str(i) + fname_end try: blk = cc.LoadMHA(fname, mType) except IOError: print 'Warning... block ' + str(i) + ' does not exist' continue blocks += blk weight3 = blk.copy() try: weight = cc.LoadMHA(imagedir + 'block{0}_as_MRI_weight_{1}.mha'.format(i, sz)) except IOError: print 'Warning, weight block does not exist' weight = ca.Image3D(blk.grid(), blk.memType()) ca.Copy(weight, blk, 0) # take red cc.SetRegionGTE(weight, weight, .1, 1) for i in xrange(3): ca.Copy(weight3, weight, i) weights += weight3 print ca.MinMax(weights) for i in xrange(3): ca.Copy(weight, weights, i) cc.SetRegionLT(weight, weight, 1, 1) ca.Copy(weights, weight, i) print ca.MinMax(weights) ca.Div_I(blocks, weights) else: # best
def DefReg(I_src, I_tar, config, memT, idConf): I_src.toType(memT) I_tar.toType(memT) # Convert to 2D spacing (because it really matters) sp2D = I_src.spacing().tolist() sp2D = ca.Vec3Df(sp2D[0], sp2D[1], 1) I_tar.setSpacing(sp2D) I_src.setSpacing(sp2D) gridReg = I_tar.grid() # Blur the images I_tar_blur = I_tar.copy() I_src_blur = I_src.copy() temp = ca.Image3D(I_tar.grid(), memT) gausFilt = ca.GaussianFilterGPU() scaleList = config.scale # Initiate the scale manager scaleManager = ca.MultiscaleManager(gridReg) for s in scaleList: scaleManager.addScaleLevel(s) if memT == ca.MEM_HOST: resampler = ca.MultiscaleResamplerGaussCPU(gridReg) else: resampler = ca.MultiscaleResamplerGaussGPU(gridReg) # Generate the scratch images scratchITar = ca.Image3D(gridReg, memT) scratchISrc = ca.Image3D(gridReg, memT) scratchI = ca.Image3D(gridReg, memT) scratchF = ca.Field3D(gridReg, memT) compF = ca.Field3D(gridReg, memT) def SetScale(scale): '''Scale Management for Multiscale''' scaleManager.set(scale) resampler.setScaleLevel(scaleManager) curGrid = scaleManager.getCurGrid() curGrid.spacing().z = 1 # Because only 2D print 'Inside setScale(). Current grid is ', curGrid if scaleManager.isLastScale(): print 'Inside setScale(): **Last Scale**' if scaleManager.isFirstScale(): print 'Inside setScale(): **First Scale**' scratchISrc.setGrid(curGrid) scratchITar.setGrid(curGrid) scratchI.setGrid(curGrid) compF.setGrid(curGrid) idConf.study.I0 = ca.Image3D(curGrid, memT) idConf.study.I1 = ca.Image3D(curGrid, memT) if scaleManager.isLastScale(): s = config.sigBlur[scaleList.index(sc)] r = config.kerBlur[scaleList.index(sc)] gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r), ca.Vec3Di(s, s, s)) gausFilt.filter(scratchITar, I_tar, temp) gausFilt.filter(scratchI, I_src, temp) # ca.Copy(scratchI, I_src) # ca.Copy(scratchITar, I_tar) else: s = config.sigBlur[scaleList.index(sc)] r = config.kerBlur[scaleList.index(sc)] gausFilt.updateParams(I_tar.size(), ca.Vec3Df(r, r, r), ca.Vec3Di(s, s, s)) gausFilt.filter(I_tar_blur, I_tar, temp) gausFilt.filter(I_src_blur, I_src, temp) resampler.downsampleImage(scratchI, I_src_blur) resampler.downsampleImage(scratchITar, I_tar_blur) if scaleManager.isFirstScale(): scratchF.setGrid(curGrid) scratchITar.setGrid(curGrid) ca.SetToIdentity(scratchF) ca.ApplyH(scratchISrc, scratchI, scratchF) else: compF.setGrid(scratchF.grid()) ca.ComposeHH(compF, scratchF, h) resampler.updateHField(scratchF) resampler.updateHField(compF) ca.Copy(scratchF, compF) ca.ApplyH(scratchISrc, scratchI, compF) for sc in scaleList: SetScale(scaleList.index(sc)) #Set the optimize parameters in the IDiff configuration object idConf.optim.Niter = config.iters[scaleList.index(sc)] idConf.optim.stepSize = config.epsReg[scaleList.index(sc)] idConf.idiff.regWeight = config.sigReg[scaleList.index(sc)] ca.Copy(idConf.study.I0, scratchISrc) ca.Copy(idConf.study.I1, scratchITar) idConf.io.plotEvery = config.iters[scaleList.index(sc)] h = IDiff.Matching.Matching(idConf) tempScr = scratchISrc.copy() ca.ApplyH(tempScr, scratchISrc, h) #Plot the images to see the change cd.DispImage(scratchISrc - scratchITar, rng=[-2, 2], title='Orig Diff', colorbar=True) cd.DispImage(tempScr - scratchITar, rng=[-2, 2], title='Reg Diff', colorbar=True) # common.DebugHere() # I_src_def = idConf.study.I0.copy() # scratchITar = idConf.study.I1 # eps = config.epsReg[scaleList.index(sc)] # sigma = config.sigReg[scaleList.index(sc)] # nIter = config.iters[scaleList.index(sc)] # # common.DebugHere() # [I_src_def, h, energy] = apps.IDiff(scratchISrc, scratchITar, eps, sigma, nIter, plot=True, verbose=1) ca.ComposeHH(scratchF, compF, h) I_src_def = idConf.study.I0.copy() return I_src_def, scratchF
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 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 BuildHGM(cf): """Worker for running Hierarchical Geodesic Model (HGM) n for group geodesic estimation on a subset of individuals. Runs HGM on this subset sequentially. The variations retuned are summed up to get update for all individuals""" size = Compute.GetMPIInfo()['size'] rank = Compute.GetMPIInfo()['rank'] name = Compute.GetMPIInfo()['name'] localRank = Compute.GetMPIInfo()['local_rank'] nodename = socket.gethostname() # prepare output directory common.Mkdir_p(os.path.dirname(cf.io.outputPrefix)) # just one reporter process on each node isReporter = rank == 0 cf.study.numSubjects = len(cf.study.subjectIntercepts) if isReporter: # Output loaded config if cf.io.outputPrefix is not None: cfstr = Config.ConfigToYAML(HGMConfigSpec, cf) with open(cf.io.outputPrefix + "parsedconfig.yaml", "w") as f: f.write(cfstr) #common.DebugHere() # if MPI check if processes are greater than number of subjects. it is okay if there are more subjects than processes if cf.compute.useMPI and (cf.study.numSubjects < cf.compute.numProcesses): raise Exception("Please don't use more processes " + "than total number of individuals") # subdivide data, create subsets for this thread to work on nodeSubjectIds = cf.study.subjectIds[rank::cf.compute.numProcesses] nodeIntercepts = cf.study.subjectIntercepts[rank::cf.compute.numProcesses] nodeSlopes = cf.study.subjectSlopes[rank::cf.compute.numProcesses] nodeBaselineTimes = cf.study.subjectBaselineTimes[rank::cf.compute. numProcesses] sys.stdout.write( "This is process %d of %d with name: %s on machinename: %s and local rank: %d.\nnodeIntercepts: %s\n nodeSlopes: %s\n nodeBaselineTimes: %s\n" % (rank, size, name, nodename, localRank, nodeIntercepts, nodeSlopes, nodeBaselineTimes)) # mem type is determined by whether or not we're using CUDA mType = ca.MEM_DEVICE if cf.compute.useCUDA else ca.MEM_HOST # load data in memory # load intercepts J = [ common.LoadITKImage(f, mType) if isinstance(f, str) else f for f in nodeIntercepts ] # load slopes n = [ common.LoadITKField(f, mType) if isinstance(f, str) else f for f in nodeSlopes ] # get imGrid from data imGrid = J[0].grid() # create time array with checkpointing info for group geodesic (t, Jind, gCpinds) = HGMSetUpTimeArray(cf.optim.nTimeStepsGroup, nodeBaselineTimes, 0.0000001) tdiscGroup = CAvmHGMCommon.HGMSetupTimeDiscretizationGroup( t, J, n, Jind, gCpinds, mType, nodeSubjectIds) # create time array with checkpointing info for residual geodesic (s, scratchInd, rCpinds) = HGMSetUpTimeArray(cf.optim.nTimeStepsResidual, [1.0], 0.0000001) tdiscResidual = CAvmHGMCommon.HGMSetupTimeDiscretizationResidual( s, rCpinds, imGrid, mType) # create group state and residual state groupState = CAvmHGMCommon.HGMGroupState( imGrid, mType, cf.vectormomentum.diffOpParamsGroup[0], cf.vectormomentum.diffOpParamsGroup[1], cf.vectormomentum.diffOpParamsGroup[2], t, cf.optim.NIterForInverse, cf.vectormomentum.varIntercept, cf.vectormomentum.varSlope, cf.vectormomentum.varInterceptReg, cf.optim.stepSizeGroup, integMethod=cf.optim.integMethodGroup) #ca.Copy(groupState.I0, common.LoadITKImage('/usr/sci/projects/ADNI/nikhil/software/vectormomentumtest/TestData/FlowerData/Longitudinal/GroupGeodesic/I0.mhd', mType)) # note that residual state is treated a scratch variable in this algorithm and reused for computing residual geodesics of multiple individual residualState = CAvmHGMCommon.HGMResidualState( None, None, imGrid, mType, cf.vectormomentum.diffOpParamsResidual[0], cf.vectormomentum.diffOpParamsResidual[1], cf.vectormomentum.diffOpParamsResidual[2], s, cf.optim.NIterForInverse, cf.vectormomentum.varIntercept, cf.vectormomentum.varSlope, cf.vectormomentum.varInterceptReg, cf.optim.stepSizeResidual, integMethod=cf.optim.integMethodResidual) # start up the memory manager for scratch variables ca.ThreadMemoryManager.init(imGrid, mType, 0) # need some host memory in np array format for MPI reductions if cf.compute.useMPI: mpiImageBuff = None if mType == ca.MEM_HOST else ca.Image3D( imGrid, ca.MEM_HOST) mpiFieldBuff = None if mType == ca.MEM_HOST else ca.Field3D( imGrid, ca.MEM_HOST) for i in range(len(groupState.t) - 1, -1, -1): if tdiscGroup[i].J is not None: indx_last_individual = i break ''' # initial template image ca.SetMem(groupState.I0, 0.0) tmp = ca.ManagedImage3D(imGrid, mType) for tdisc in tdiscGroup: if tdisc.J is not None: ca.Copy(tmp, tdisc.J) groupState.I0 += tmp del tmp if cf.compute.useMPI: Compute.Reduce(groupState.I0, mpiImageBuff) # divide by total num subjects groupState.I0 /= cf.study.numSubjects ''' # run the loop for it in range(cf.optim.Niter): # compute HGM variation for group HGMGroupVariation(groupState, tdiscGroup, residualState, tdiscResidual, cf.io.outputPrefix, rank, it) common.CheckCUDAError("Error after HGM iteration") # compute gradient for momenta (m is used as scratch) # if there are multiple nodes we'll need to sum across processes now if cf.compute.useMPI: # do an MPI sum Compute.Reduce(groupState.sumSplatI, mpiImageBuff) Compute.Reduce(groupState.sumJac, mpiImageBuff) Compute.Reduce(groupState.madj, mpiFieldBuff) # also sum up energies of other nodes # intercept Eintercept = np.array([groupState.EnergyHistory[-1][1]]) mpi4py.MPI.COMM_WORLD.Allreduce(mpi4py.MPI.IN_PLACE, Eintercept, op=mpi4py.MPI.SUM) groupState.EnergyHistory[-1][1] = Eintercept[0] Eslope = np.array([groupState.EnergyHistory[-1][2]]) mpi4py.MPI.COMM_WORLD.Allreduce(mpi4py.MPI.IN_PLACE, Eslope, op=mpi4py.MPI.SUM) groupState.EnergyHistory[-1][2] = Eslope[0] ca.Copy(groupState.m, groupState.m0) groupState.diffOp.applyInverseOperator(groupState.m) ca.Sub_I(groupState.m, groupState.madj) #groupState.diffOp.applyOperator(groupState.m) # now take gradient step in momenta for group if cf.optim.method == 'FIXEDGD': # take fixed stepsize gradient step ca.Add_MulC_I(groupState.m0, groupState.m, -cf.optim.stepSizeGroup) else: raise Exception("Unknown optimization scheme: " + cf.optim.method) # end if # now divide to get the new base image for group ca.Div(groupState.I0, groupState.sumSplatI, groupState.sumJac) # keep track of energy in this iteration if isReporter and cf.io.plotEvery > 0 and (( (it + 1) % cf.io.plotEvery == 0) or (it == cf.optim.Niter - 1)): HGMPlots(cf, groupState, tdiscGroup, residualState, tdiscResidual, indx_last_individual, writeOutput=True) if isReporter: (VEnergy, IEnergy, SEnergy) = groupState.EnergyHistory[-1] print datetime.datetime.now().time( ), " Iter", it, "of", cf.optim.Niter, ":", VEnergy + IEnergy + SEnergy, '(Total) = ', VEnergy, '(Vector) + ', IEnergy, '(Intercept) + ', SEnergy, '(Slope)' # write output images and fields HGMWriteOutput(cf, groupState, tdiscGroup, isReporter)
def HGMPlots(cf, groupState, tDiscGroup, residualState, tDiscResidual, index_individual, writeOutput=True): """ Do some summary plots for HGM """ #ENERGY fig = plt.figure(1) plt.clf() fig.patch.set_facecolor('white') TE = [sum(x) for x in groupState.EnergyHistory] VE = [row[0] for row in groupState.EnergyHistory] IE = [row[1] for row in groupState.EnergyHistory] SE = [row[2] for row in groupState.EnergyHistory] TE = TE[1:] VE = VE[1:] IE = IE[1:] SE = SE[1:] 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('Intercept Energy') plt.hold(False) plt.subplot(2, 2, 4) plt.plot(SE) plt.title('Slope Energy') plt.hold(False) plt.draw() plt.show() if cf.io.outputPrefix != None and writeOutput: plt.savefig(cf.io.outputPrefix + 'energy.pdf') # GROUP INITIAL CONDITIONS and PSI and PSI inv # shoot group geodesic forward CAvmHGMCommon.HGMIntegrateGeodesic(groupState.m0, groupState.t, groupState.diffOp, groupState.m, groupState.g, groupState.ginv, tDiscGroup, groupState.Ninv, groupState.integMethod) fig = plt.figure(2) plt.clf() fig.patch.set_facecolor('white') plt.subplot(2, 2, 1) display.DispImage(groupState.I0, 'I0', newFig=False, sliceIdx=cf.io.plotSlice) plt.subplot(2, 2, 2) ca.ApplyH(groupState.I, groupState.I0, groupState.ginv) display.DispImage(groupState.I, 'I1', newFig=False, sliceIdx=cf.io.plotSlice) plt.subplot(2, 2, 3) display.GridPlot(groupState.ginv, every=cf.io.quiverEvery, color='k', sliceIdx=cf.io.plotSlice, isVF=False) plt.axis('equal') plt.axis('off') plt.title('psi^{-1}') plt.subplot(2, 2, 4) display.GridPlot(groupState.g, every=cf.io.quiverEvery, color='k', sliceIdx=cf.io.plotSlice, isVF=False) plt.axis('equal') plt.axis('off') plt.title('psi') if cf.io.outputPrefix != None and writeOutput: plt.savefig(cf.io.outputPrefix + 'groupdef.pdf') # RESIDUAL INITIAL CONDITIONS and RHO and RHO inv ca.ApplyH(groupState.I, groupState.I0, groupState.ginv) residualState.J0 = groupState.I residualState.p0 = tDiscGroup[index_individual].p0 CAvmHGMCommon.HGMIntegrateGeodesic(residualState.p0, residualState.s, residualState.diffOp, residualState.p, residualState.rho, residualState.rhoinv, tDiscResidual, residualState.Ninv, residualState.integMethod) fig = plt.figure(3) plt.clf() fig.patch.set_facecolor('white') plt.subplot(2, 2, 1) display.DispImage(residualState.J0, 'J0', newFig=False, sliceIdx=cf.io.plotSlice) plt.subplot(2, 2, 2) ca.ApplyH(residualState.J, residualState.J0, residualState.rhoinv) display.DispImage(residualState.J, 'J1', newFig=False, sliceIdx=cf.io.plotSlice) plt.subplot(2, 2, 3) display.GridPlot(residualState.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(residualState.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 + 'resdef.pdf') # MATCHING DIFFERENCE IMAGES grid = groupState.I0.grid() mType = groupState.I0.memType() imdiff = ca.ManagedImage3D(grid, mType) vecdiff = ca.ManagedField3D(grid, mType) # Intercept matching ca.Copy(imdiff, residualState.J) ca.Sub_I(imdiff, tDiscGroup[index_individual].J) fig = plt.figure(4) plt.clf() fig.patch.set_facecolor('white') plt.subplot(1, 3, 1) display.DispImage(residualState.J0, 'Source J0', newFig=False, sliceIdx=cf.io.plotSlice) plt.colorbar() plt.subplot(1, 3, 2) display.DispImage(tDiscGroup[index_individual].J, '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 + 'diffintercept.pdf') # Slope matching ''' ca.CoAd(groupState.m,groupState.ginv,groupState.m0) ca.CoAd(vecdiff,residualState.rhoinv,groupState.m) n0 = ca.Field3D(grid, ca.MEM_HOST) n1 = ca.Field3D(grid, ca.MEM_HOST) ca.Copy(n0,groupState.m) ca.Copy(n1,tDiscGroup[index_individual].n) ca.Sub_I(vecdiff, tDiscGroup[index_individual].n) vecdiff.toType(ca.MEM_HOST) n0_x, n0_y, n0_z = n0.asnp() n1_x, n1_y, n1_z = n1.asnp() diff_x, diff_y, diff_z = vecdiff.asnp() fig = plt.figure(5) plt.clf() fig.patch.set_facecolor('white') plt.subplot(2,3,1) plt.imshow(np.squeeze(n0_x)); plt.colorbar(); plt.title('X: Source n0 ') plt.subplot(2,3,2) plt.imshow(np.squeeze(n1_x)); plt.colorbar(); plt.title('X: Target n1') plt.subplot(2,3,3) plt.imshow(np.squeeze(diff_x)); plt.colorbar(); plt.title('X: rho.n0-n1') plt.subplot(2,3,4) plt.imshow(np.squeeze(n0_y)); plt.colorbar(); plt.title('Y: Source n0') plt.subplot(2,3,5) plt.imshow(np.squeeze(n1_y)); plt.colorbar(); plt.title('Y: Target n1') plt.subplot(2,3,6) plt.imshow(np.squeeze(diff_y)); plt.colorbar(); plt.title('Y: rho.n0-n1') if cf.io.outputPrefix != None and writeOutput: plt.savefig(cf.io.outputPrefix+'diffslope.pdf') ''' del imdiff del vecdiff
Imprev = cc.LoadTIFF(filelist[0], mType, ds) origin = [(Imprev.grid().size().x+1)/2.0, # origin for Affine matrix (Imprev.grid().size().y+1)/2.0, (Imprev.grid().size().z+1)/2.0] scratchI = ca.Image3D(Imprev.grid(), Imprev.memType()) scratchI2 = ca.Image3D(Imprev.grid(), Imprev.memType()) # initialize dictionary Adict = {'origin': origin} Adict[files.get_file_dist(filelist[0])] = np.identity(3) # if 'block1' in filelist[0]: # move first image in block 1 if block == 1: tcentx, tcenty = cc.CenterImage(Imprev) ca.Copy(scratchI, Imprev) # first moves image up, second moves image left t = ca.Vec3Df(-75, 55, 0) # double check this! ca.ComposeTranslation(Imprev, scratchI, t) ttot = [tcentx + t.x, tcenty + t.y] Adict[files.get_file_dist(filelist[0])] = np.array([[1, 0, tcentx + t.x], [0, 1, tcenty + t.y], [0, 0, 1]]) dist_prev = -30 # assure correct numbering for filename in filelist[1:]: dist = files.get_file_dist(filename) num_blanks = (dist - dist_prev)/30 - 1 for _i in xrange(num_blanks): print 'blank'
# # Convert the landmarks to real coordinates and exchange the ordering of the so live is going to T2 # realLM[:,1] = realLM[:,1] - 127.5 # flipLM = np.fliplr(realLM) # # Solve for the TPS based off of the landmakrs # spline = SolveSpline(flipLM) # h = SplineToHField(spline, T2Grid, memT) # print ca.MinMax(h) # liveDef = T2.copy() # cc.ApplyHReal(liveDef,live,h) # Variance equalize the volumes and blur the live T2_VE = ca.Image3D(T2.grid(), memT) live_VE = ca.Image3D(liveDef.grid(), memT) ca.Copy(T2_VE, T2) cc.VarianceEqualize_I(T2_VE, sigma=5) ca.Copy(live_VE, liveDef) cc.VarianceEqualize_I(live_VE, sigma=5) gausfilt = ca.GaussianFilterGPU() gausfilt.updateParams(live_VE.size(), ca.Vec3Df(3, 3, 3), ca.Vec3Di(3, 3, 3)) live_VEfilt = ca.Image3D(live_VE.grid(), memT) temp = ca.Image3D(live_VE.grid(), memT) gausfilt.filter(live_VEfilt, live_VE, temp) dispslice = [128, 120, 128] # Display some initial images cd.Disp3Pane(live_VEfilt, rng=[-3, 3], sliceIdx=dispslice, title='Live VE Filtered')
def WarpGradient(p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts): # shoot the geodesic forward CAvmCommon.IntegrateGeodesic(p.m0,t,p.diffOp, \ p.m, p.g, p.ginv,\ p.scratchV1, p.scratchV2,p. scratchV3,\ cpstates, cpinds,\ Ninv=p.nInv, integMethod = p.integMethod, RK4=p.scratchV4,scratchG=p.scratchV5) IEnergy = 0.0 # compute residuals for each measurement timepoint along with computing energy for i in range(len(Imsmts)): if msmtinds[i] != -1: (g, ginv) = cpstates[msmtinds[i]] ca.ApplyH(gradAtMsmts[i], p.I0, ginv) ca.Sub_I(gradAtMsmts[i], Imsmts[i]) # while we have residual, save the image energy IEnergy += ca.Sum2( gradAtMsmts[i]) / (2 * p.sigma * p.sigma * float(p.I0.nVox())) ca.DivC_I(gradAtMsmts[i], p.sigma * p.sigma) # gradient at measurement elif msmtinds[i] == -1: ca.Copy(gradAtMsmts[i], p.I0) ca.Sub_I(gradAtMsmts[i], Imsmts[i]) # while we have residual, save the image energy IEnergy += ca.Sum2( gradAtMsmts[i]) / (2 * p.sigma * p.sigma * float(p.I0.nVox())) ca.DivC_I(gradAtMsmts[i], p.sigma * p.sigma) # gradient at measurement # integrate backward CAvmCommon.IntegrateAdjoints(p.Iadj,p.madj,\ p.I,p.m,p.Iadjtmp, p.madjtmp,p.scratchV1,\ p.scratchV2,p.scratchV3,\ p.I0,p.m0,\ t, cpstates, cpinds,\ gradAtMsmts,msmtinds,\ p.diffOp,\ p.integMethod, p.nInv, \ scratchV3=p.scratchV7, scratchV4=p.g,scratchV5=p.ginv,scratchV6=p.scratchV8, scratchV7=p.scratchV9, \ scratchV8=p.scratchV10,scratchV9=p.scratchV11,\ RK4=p.scratchV4, scratchG=p.scratchV5, scratchGinv=p.scratchV6,\ scratchI = p.scratchI1) # compute gradient ca.Copy(p.scratchV1, p.m0) p.diffOp.applyInverseOperator(p.scratchV1) # while we have velocity, save the vector energy VEnergy = 0.5 * ca.Dot(p.m0, p.scratchV1) / float(p.I0.nVox()) ca.Sub_I(p.scratchV1, p.madj) #p.diffOp.applyOperator(p.scratchV1) # compute closed from terms for image update # p.Iadjtmp and p.I will be used as scratch images scratchI = p.scratchI1 #reference assigned imOnes = p.I #reference assigned ca.SetMem(imOnes, 1.0) ca.SetMem(p.sumSplatI, 0.0) ca.SetMem(p.sumJac, 0.0) #common.DebugHere() for i in range(len(Imsmts)): # TODO: check these indexings for cases when timepoint 0 # is not checkpointed if msmtinds[i] != -1: (g, ginv) = cpstates[msmtinds[i]] CAvmCommon.SplatSafe(scratchI, ginv, Imsmts[i]) ca.Add_I(p.sumSplatI, scratchI) CAvmCommon.SplatSafe(scratchI, ginv, imOnes) ca.Add_I(p.sumJac, scratchI) elif msmtinds[i] == -1: ca.Add_I(p.sumSplatI, Imsmts[i]) ca.Add_I(p.sumJac, imOnes) return (p.scratchV1, p.sumJac, p.sumSplatI, VEnergy, IEnergy)
def GeoRegIteration(subid, cf, p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts, EnergyHistory, it): # compute gradient for regression (grad_m, sumJac, sumSplatI, VEnergy, IEnergy) = GeoRegGradient(p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts) # do energy related stuff for printing and bookkeeping #if it>0: EnergyHistory.append([VEnergy + IEnergy, VEnergy, IEnergy]) print VEnergy + IEnergy, '(Total) = ', VEnergy, '(Vector)+', IEnergy, '(Image)' # plot some stuff if cf.io.plotEvery > 0 and (((it + 1) % cf.io.plotEvery) == 0 or it == cf.optim.Niter - 1): GeoRegPlots(subid, cf, p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts, EnergyHistory) # end if if cf.optim.method == 'FIXEDGD': # automatic stepsize selection in the first three steps if it == 1: # TODO: BEWARE There are hardcoded numbers here for 2D and 3D #first find max absolute value across voxels in gradient temp = ca.Field3D(grad_m.grid(), ca.MEM_HOST) ca.Copy(temp, grad_m) temp_x, temp_y, temp_z = temp.asnp() temp1 = np.square(temp_x.flatten()) + np.square( temp_y.flatten()) + np.square(temp_z.flatten()) medianval = np.median(temp1[temp1 > 0.0000000001]) del temp, temp1, temp_x, temp_y, temp_z #2D images for 2000 iters #p.stepSize = float(0.000000002*medianval) #3D images for 2000 iters p.stepSize = float(0.000002 * medianval) print 'rank:', Compute.GetMPIInfo( )['rank'], ', localRank:', Compute.GetMPIInfo( )['local_rank'], 'subid: ', subid, ' Selecting initial step size in the beginning to be ', str( p.stepSize) if it > 3: totalEnergyDiff = EnergyHistory[-1][0] - EnergyHistory[-2][0] if totalEnergyDiff > 0.0: if cf.optim.maxPert is not None: print 'rank:', Compute.GetMPIInfo( )['rank'], ', localRank:', Compute.GetMPIInfo( )['local_rank'], 'subid: ', subid, ' Reducing stepsize for gradient descent by ', str( cf.optim.maxPert * 100), '%. The new step size is ', str( p.stepSize * (1 - cf.optim.maxPert)) p.stepSize = p.stepSize * (1 - cf.optim.maxPert) # take gradient descent step ca.Add_MulC_I(p.m0, grad_m, -p.stepSize) else: raise Exception("Unknown optimization scheme: " + cf.optim.optMethod) # end if # now divide to get new base image ca.Div(p.I0, sumSplatI, sumJac) return (EnergyHistory)