def _reconstruct(self, observation, out): observation = self.observation_space.element(observation) out[:] = self.x0 gradient = Gradient(self.op.domain) L = [self.op, gradient] f = ZeroFunctional(self.op.domain) l2_norm = 0.5 * L2NormSquared(self.op.range).translated(observation) l12_norm = self.lam * GroupL1Norm(gradient.range) g = [l2_norm, l12_norm] op_norm = power_method_opnorm(self.op, maxiter=20) gradient_norm = power_method_opnorm(gradient, maxiter=20) sigma_ray_trafo = 45.0 / op_norm**2 sigma_gradient = 45.0 / gradient_norm**2 sigma = [sigma_ray_trafo, sigma_gradient] h = ZeroFunctional(self.op.domain) forward_backward_pd(out, f, g, L, h, self.tau, sigma, self.niter, callback=self.callback) return out
def _reconstruct(self, observation, out): observation = self.observation_space.element(observation) out_ = out if out not in self.reco_space: out_ = self.reco_space.zero() out_[:] = self.x0 gradient = Gradient(self.op.domain) L = BroadcastOperator(self.op, gradient) f = ZeroFunctional(self.op.domain) l2_norm = L2NormSquared(self.op.range).translated(observation) l1_norm = self.lam * L1Norm(gradient.range) g = SeparableSum(l2_norm, l1_norm) op_norm = 1.1 * power_method_opnorm(L, maxiter=20) sigma = self.tau * op_norm**2 admm.admm_linearized(out_, f, g, L, self.tau, sigma, self.niter, callback=self.callback) if out not in self.reco_space: out[:] = out_ return out
def _reconstruct(self, observation, out): # The proximal_gradient and accelerated_proximal_gradient methods # from ODL have as input the function, which needs to be minimized # (and not the forward operator itself). Therefore, we calculate the # discrepancy ||Ax-b||_2^2. Note that the terms `f` and `g` are # switched in odl compared to the usage in the FISTA paper # (https://epubs.siam.org/doi/abs/10.1137/080716542). observation = self.observation_space.element(observation) out[:] = self.x0 l2_norm_sq_trans = L2NormSquared(self.op.range).translated(observation) discrepancy = l2_norm_sq_trans * self.op if not self.accelerated: proximal_gradient_solvers.proximal_gradient(out, self.reg, discrepancy, self.gamma, self.niter, callback=self.callback, lam=self.lam) else: proximal_gradient_solvers.accelerated_proximal_gradient( out, self.reg, discrepancy, self.gamma, self.niter, callback=self.callback, lam=self.lam) return out
def __call__(self, x): ret = 0 xim = x[:self.N] for i in range(self.N): if self.alpha[i] != 0: xi = xim[i] res = self.residual(xi, i) ret += 0.5 * self.alpha[i] * L2NormSquared(res.space)(res) return ret
def __call__(self, x): # x is space time element im x vf ret = 0. xim = x[:self.N] xvf = x[self.N:] for i in range(self.N - 1): ximi = xim[i] ximii = xim[i + 1] xvfi = xvf[i] res = self.residual(ximii, ximi, xvfi) ret += 0.5 * L2NormSquared(res.space)(res) return self.alpha * ret
def _reconstruct(self, observation, out): observation = self.observation_space.element(observation) out[:] = self.x0 l2_norm = L2NormSquared(self.op.range) discrepancy = l2_norm * (self.op - observation) gradient = Gradient(self.op.domain) l1_norm = GroupL1Norm(gradient.range) smoothed_l1 = MoreauEnvelope(l1_norm, sigma=0.03) regularizer = smoothed_l1 * gradient f = discrepancy + self.lam * regularizer opnorm = power_method_opnorm(self.op) hessinv_estimate = ScalingOperator(self.op.domain, 1 / opnorm**2) newton.bfgs_method(f, out, maxiter=self.niter, hessinv_estimate=hessinv_estimate, callback=self.callback) return out
def _reconstruct(self, observation, out): observation = self.observation_space.element(observation) out[:] = self.x0 gradient = Gradient(self.op.domain) L = BroadcastOperator(self.op, gradient) f = ZeroFunctional(self.op.domain) l2_norm = L2NormSquared(self.op.range).translated(observation) l1_norm = self.lam * L1Norm(gradient.range) g = [l2_norm, l1_norm] tau, sigma = douglas_rachford.douglas_rachford_pd_stepsize(L) douglas_rachford.douglas_rachford_pd(out, f, g, L, self.niter, tau, sigma, callback=self.callback) return out
def _reconstruct(self, observation, out): observation = self.observation_space.element(observation) out[:] = self.x0 gradient = Gradient(self.op.domain) L = BroadcastOperator(self.op, gradient) f = ZeroFunctional(self.op.domain) l2_norm = L2NormSquared(self.op.range).translated(observation) l1_norm = self.lam * L1Norm(gradient.range) g = SeparableSum(l2_norm, l1_norm) tau, sigma = primal_dual_hybrid_gradient.pdhg_stepsize(L) primal_dual_hybrid_gradient.pdhg(out, f, g, L, self.niter, tau, sigma, callback=self.callback) return out
def __init__(self, space, data, forward=None): self.space = space self.image_space = self.space[0] self.affine_space = self.space[1] self.rest_space = self.space[2] self.deformation_space = ProductSpace(self.affine_space, self.rest_space) self.data = data if forward is None: self.forward = IdentityOperator(self.image_space) else: self.forward = forward self.datafit = 0.5 * L2NormSquared(self.image_space).translated( self.data) self.embedding_affine_rest = ops.Embedding_Affine_Rest( self.deformation_space, self.image_space.tangent_bundle) self.embedding_affine = ops.Embedding_Affine( self.affine_space, self.image_space.tangent_bundle) super(DataFitL2DispAffRest, self).__init__(space=space, linear=False, grad_lipschitz=np.nan)
def __init__(self, space, data, forward=None): self.space = space self.image_space = self.space[0] self.affine_space = self.space[1] self.data = data if forward is None: self.forward = IdentityOperator(self.image_space) else: self.forward = forward self.datafit = 0.5 * L2NormSquared(data.space).translated(self.data) if isinstance(self.image_space, odl.ProductSpace): tangent_bundle = self.image_space[0].tangent_bundle else: tangent_bundle = self.image_space.tangent_bundle self.embedding = ops.Embedding_Affine(self.affine_space, tangent_bundle) super(DataFitL2Disp, self).__init__(space=space, linear=False, grad_lipschitz=np.nan)
def minimization_alpha(dataset, reg, alpha, energy, nangles): alg_name = 'fbs' sinfo_type = 'tv' # can be choose to be 'tv' or 'fbp' alg = '{}{}'.format(alg_name, reg) folder_data = './data/{}'.format(dataset) variables = {} with open('{}/parameters.txt'.format(folder_data)) as data_file: for line in data_file: name, value = line.split(" ") variables[name] = float(value) dom_width = variables["dom_width"] ndet = int(variables['ndet']) # Data and reconstruction size n = 512 # Change these values if a different side information TV-reg is used if dataset == 'xcat': if sinfo_type == 'fbp': sinfo_name = 'fbp' elif sinfo_type == 'tv': sinfo_name = '0_1' elif dataset == 'bird': sinfo_name = '0_03' # Folder to save alpha_folder = './results/{}/{}/{}_angles/' \ '{}_alphas_{}'.format(dataset, alg_name, nangles, energy, reg) st = 1 sett = { 'fbsTV': { 'outer_iter': 500, 'inner_iter': 200, 'tol': 1e-5 }, 'fbsdTV': { 'outer_iter': 500, 'inner_iter': 200, 'tol': 1e-5 } } if sinfo_name == 'fbp': alpha_folder = '{}/fbp_side_info'.format(alpha_folder) if not os.path.exists(alpha_folder): os.makedirs(alpha_folder) niter, iter_save_x, iter_save_meas, iter_plot = {}, {}, {}, {} sett_keys = sett.keys() for a in sett_keys: niter[a] = sett[a]['outer_iter'] + 1 iter_save_x[a] = range(0, niter[a], 1) iter_save_meas[a] = range(0, niter[a], 1) iter_plot[a] = range(0, niter[a], 5) # %% gt_fbp = {} gt_tv = {} if dataset == 'bird': # FBP gt_fbp[energy] = np.load('{}/{}_{}x{}_FBP_' 'reference.npy'.format( folder_data, energy, n, n)) # TV reconstruction ref_alphas = {'E0': 5e-3, 'E1': 2e-3, 'E2': 2e-3} ref_alpha = ref_alphas[energy] name = '{}_{}x{}_reference_reconstruction'.format(energy, n, n) name = name + '_alpha_' + str(ref_alpha).replace('.', '_') ref_dir = '{}/{}.npy'.format(folder_data, name) gt_tv[energy] = np.load(ref_dir)[0] elif dataset == 'xcat': # FBP gt_fbp[energy] = np.load('{}/{}_{}x{}_FBP_' 'reference.npy'.format( folder_data, energy, n, n)) gt_tv[energy] = gt_fbp[energy] U = odl.uniform_discr([-dom_width * 0.5, -dom_width * 0.5], [dom_width * 0.5, dom_width * 0.5], (n, n)) # %% # dTV parameters and side information eta = 1e-2 eta_str = '{0:.1e}'.format(eta) eta_str = eta_str.replace('-', '_') if sinfo_name == 'fbp': sinfo = np.load('{}/sinfo_fbp_{}x{}' '.npy'.format(folder_data, nangles, ndet)) else: sinfo = np.load('{}/sinfo_TV_reconstruction_{}_d{}x{}_m{}' '.npy'.format(folder_data, sinfo_name, nangles, ndet, n)) D = misc.dTV(U, sinfo, eta) # Data data = {} name_data = np.load('{}/sinograms_{}x{}.npy'.format( folder_data, nangles, ndet)) sinogram = name_data.item() # Operators and optimization parameters g = {} Lipschitz_cte = {} R = misc.forward_operator(dataset, 'sample', nangles) data[energy] = R.range.element(sinogram[energy]) data_space = data[energy].space data_fit = 0.5 * L2NormSquared(data_space).translated(data[energy]) g[energy] = data_fit * R Lipschitz_cte[energy] = R.norm(estimate=True)**2 sigma_fbs = 1 / Lipschitz_cte[energy] # Run algorithm for different values of alpha alpha_str = '{0:.1e}'.format(alpha) alpha_str = alpha_str.replace('.', '_') alpha_name = 'alpha_{}'.format(alpha_str) name = '{}/{}.npy'.format(alpha_folder, alpha_name) # if os.path.isfile(name): # os.system('say "Esta configuracion ya fue ejecutada"') # return print('\n Solving reconstruction using alpha = {}\n'.format(alpha)) fit_value = g[energy] prox_options = {} prox_options['niter'] = sett[alg]['inner_iter'] prox_options['tol'] = sett[alg]['tol'] prox_options['name'] = 'FGP' prox_options['warmstart'] = True prox_options['p'] = None alpha = alpha strong_convexity = 0 if alg == 'fbsdTV': grad = D elif alg == 'fbsTV': grad = None Ru = TVnn(U, alpha=alpha, prox_options=prox_options, grad=grad, strong_convexity=strong_convexity) function_value = g[energy] + Ru def ssim_val(x, x_truth=gt_tv[energy]): return ssim(x, x_truth) ssfolder = '{}/{}'.format(alpha_folder, alpha_name) if not os.path.exists(ssfolder): os.makedirs(ssfolder) cb1 = odl.solvers.CallbackPrintIteration cb2 = odl.solvers.CallbackPrintTiming cb3 = odl.solvers.CallbackPrint cb3b = odl.solvers.CallbackPrint # cb4 = misc.CallbackStoreA(alg=alg, iter_save_x=iter_save_x[alg], # iter_save_meas=iter_save_meas[alg], # iter_plot=None, # x_truth_tv=gt_tv[energy], # x_truth_fbp=gt_fbp[energy], ssfolder=ssfolder, # vmax=None, cmap=None) cb = (cb1(fmt='iter:{:4d}', step=st, end=', ') & cb2(fmt='time: {:5.2f} s', cumulative=True, step=st, end=', ') & cb3(function_value, fmt='f(x)={0:.4g}', step=st, end=', ') & cb3(fit_value, fmt='data_fit(x)={0:.4g}', step=st, end=', ') & cb3b(ssim_val, fmt='ssim={0:.4g}', step=st)) x = U.one() misc.fbs(U, g[energy], Ru, sigma_fbs, g_grad=None, x=x, niter=niter[alg], callback=cb) solution = x name = '{}/{}.npy'.format(alpha_folder, alpha_name) np.save(name, solution)