def Matching(cf): if cf.compute.useCUDA and cf.compute.gpuID is not None: ca.SetCUDADevice(cf.compute.gpuID) # 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(MatchingConfigSpec, cf) with open(cf.io.outputPrefix + "parsedconfig.yaml", "w") as f: f.write(cfstr) mType = ca.MEM_DEVICE if cf.compute.useCUDA else ca.MEM_HOST I0 = common.LoadITKImage(cf.study.I0, mType) I1 = common.LoadITKImage(cf.study.I1, mType) #ca.DivC_I(I0,255.0) #ca.DivC_I(I1,255.0) grid = I0.grid() ca.ThreadMemoryManager.init(grid, mType, 1) #common.DebugHere() # TODO: need to work on these t = [x*1./cf.optim.nTimeSteps for x in range(cf.optim.nTimeSteps+1)] checkpointinds = range(1,len(t)) checkpointstates = [(ca.Field3D(grid,mType),ca.Field3D(grid,mType)) for idx in checkpointinds] p = MatchingVariables(I0,I1, cf.vectormomentum.sigma, t,checkpointinds, checkpointstates, cf.vectormomentum.diffOpParams[0], cf.vectormomentum.diffOpParams[1], cf.vectormomentum.diffOpParams[2], cf.optim.Niter, cf.optim.stepSize, cf.optim.maxPert, cf.optim.nTimeSteps, integMethod = cf.optim.integMethod, optMethod=cf.optim.method, nInv=cf.optim.NIterForInverse,plotEvery=cf.io.plotEvery, plotSlice = cf.io.plotSlice, quiverEvery = cf.io.quiverEvery, outputPrefix = cf.io.outputPrefix) RunMatching(p) # write output if cf.io.outputPrefix is not None: # reset all variables by shooting once, may have been overwritten 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) common.SaveITKField(p.m0, cf.io.outputPrefix+"m0.mhd") common.SaveITKField(p.ginv, cf.io.outputPrefix+"phiinv.mhd") common.SaveITKField(p.g, cf.io.outputPrefix+"phi.mhd")
def AtlasWriteOutput(cf, atlas, m_array, nodeSubjectsIds, isReporter): # save initial momenta for all individuals for itsub in range(len(nodeSubjectsIds)): common.SaveITKField( m_array[itsub], cf.io.outputPrefix + str(nodeSubjectsIds[itsub]).replace('.', '_') + "_m0.mhd") # save the atlas if isReporter: common.SaveITKImage(atlas, cf.io.outputPrefix + "atlas.mhd")
def HGMWriteOutput(cf, groupState, tDiscGroup, isReporter): # save initial momenta for residual geodesics, p, for all individuals for i in range(len(groupState.t)): if tDiscGroup[i].J is not None: common.SaveITKField( tDiscGroup[i].p0, cf.io.outputPrefix + str(tDiscGroup[i].subjectId).replace('.', '_') + "_p0.mhd") # write individual's energy history energyFilename = cf.io.outputPrefix + str( tDiscGroup[i].subjectId).replace('.', '_') + "ResidualEnergy.csv" HGMWriteEnergyHistoryToFile(tDiscGroup[i].Energy, energyFilename) # save initial image and momenta for group gedoesic if isReporter: common.SaveITKImage(groupState.I0, cf.io.outputPrefix + "I0.mhd") common.SaveITKField(groupState.m0, cf.io.outputPrefix + "m0.mhd") # write energy history energyFilename = cf.io.outputPrefix + "TotalEnergyHistory.csv" HGMWriteEnergyHistoryToFile(groupState.EnergyHistory, energyFilename)
def GeoRegWriteOuput(subjectId, cf, p, t, Imsmts, cpinds, cpstates, msmtinds, gradAtMsmts, EnergyHistory): # save initial image and momenta for regression geodesic common.SaveITKImage(p.I0, cf.io.outputPrefix + subjectId + "I0.mhd") common.SaveITKField(p.m0, cf.io.outputPrefix + subjectId + "m0.mhd") # save residual images for regression geodesic # TODO: # write Energy details energyFilename = cf.io.outputPrefix + subjectId + "Energy.csv" with open(energyFilename, 'w') as f: csv_writer = csv.writer(f, delimiter='\t') csv_writer.writerows(EnergyHistory)
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 MatchingImageMomentaWriteOuput(cf, geodesicState): # save momenta for the gedoesic common.SaveITKField(geodesicState.p0, cf.io.outputPrefix + "p0.mhd")
def write_result(result, output_prefix): common.SaveITKImage(result['I1'], output_prefix+"I1.mhd") common.SaveITKField(result['phiinv'], output_prefix+"phiinv.mhd")
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 predict_image(args): if (args.use_CPU_for_shooting): mType = ca.MEM_HOST else: mType = ca.MEM_DEVICE # load the prediction network predict_network_config = torch.load(args.prediction_parameter) prediction_net = create_net(args, predict_network_config) batch_size = args.batch_size patch_size = predict_network_config['patch_size'] input_batch = torch.zeros(batch_size, 2, patch_size, patch_size, patch_size).cuda() # start prediction for i in range(0, len(args.moving_image)): common.Mkdir_p(os.path.dirname(args.output_prefix[i])) if (args.affine_align): # Perform affine registration to both moving and target image to the ICBM152 atlas space. # Registration is done using Niftireg. call([ "reg_aladin", "-noSym", "-speeeeed", "-ref", args.atlas, "-flo", args.moving_image[i], "-res", args.output_prefix[i] + "moving_affine.nii", "-aff", args.output_prefix[i] + 'moving_affine_transform.txt' ]) call([ "reg_aladin", "-noSym", "-speeeeed", "-ref", args.atlas, "-flo", args.target_image[i], "-res", args.output_prefix[i] + "target_affine.nii", "-aff", args.output_prefix[i] + 'target_affine_transform.txt' ]) moving_image = common.LoadITKImage( args.output_prefix[i] + "moving_affine.nii", mType) target_image = common.LoadITKImage( args.output_prefix[i] + "target_affine.nii", mType) else: moving_image = common.LoadITKImage(args.moving_image[i], mType) target_image = common.LoadITKImage(args.target_image[i], mType) #preprocessing of the image moving_image_np = preprocess_image(moving_image, args.histeq) target_image_np = preprocess_image(target_image, args.histeq) grid = moving_image.grid() moving_image_processed = common.ImFromNPArr(moving_image_np, mType) target_image_processed = common.ImFromNPArr(target_image_np, mType) moving_image.setGrid(grid) target_image.setGrid(grid) predict_transform_space = False if 'matlab_t7' in predict_network_config: predict_transform_space = True # run actual prediction prediction_result = util.predict_momentum(moving_image_np, target_image_np, input_batch, batch_size, patch_size, prediction_net, predict_transform_space) m0 = prediction_result['image_space'] m0_reg = common.FieldFromNPArr(prediction_result['image_space'], mType) registration_result = registration_methods.geodesic_shooting( moving_image_processed, target_image_processed, m0_reg, args.shoot_steps, mType, predict_network_config) phi = common.AsNPCopy(registration_result['phiinv']) phi_square = np.power(phi, 2) for sample_iter in range(1, args.samples): print(sample_iter) prediction_result = util.predict_momentum( moving_image_np, target_image_np, input_batch, batch_size, patch_size, prediction_net, predict_transform_space) m0 += prediction_result['image_space'] m0_reg = common.FieldFromNPArr(prediction_result['image_space'], mType) registration_result = registration_methods.geodesic_shooting( moving_image_processed, target_image_processed, m0_reg, args.shoot_steps, mType, predict_network_config) phi += common.AsNPCopy(registration_result['phiinv']) phi_square += np.power( common.AsNPCopy(registration_result['phiinv']), 2) m0_mean = np.divide(m0, args.samples) m0_reg = common.FieldFromNPArr(m0_mean, mType) registration_result = registration_methods.geodesic_shooting( moving_image_processed, target_image_processed, m0_reg, args.shoot_steps, mType, predict_network_config) phi_mean = registration_result['phiinv'] phi_var = np.divide(phi_square, args.samples) - np.power( np.divide(phi, args.samples), 2) #save result common.SaveITKImage(registration_result['I1'], args.output_prefix[i] + "I1.mhd") common.SaveITKField(phi_mean, args.output_prefix[i] + "phiinv_mean.mhd") common.SaveITKField(common.FieldFromNPArr(phi_var, mType), args.output_prefix[i] + "phiinv_var.mhd")